3

我只是想强制转换为数字as.numeric ——即,应用于任何以 a1作为第一个条目(即一个字符)的列。所以我希望转向:

tibble(a = c("1", "2"), b = c("Fred", "Kevin"), c = 1:2)

进入

tibble(a = 1:2, b = c("Fred", "Kevin"), c = 1:2)
4

4 回答 4

3

你可以使用dplyr

library(dplyr)

data %>% 
  mutate(across(where(~ first(.x) == "1" & !is.na(first(.x))), as.numeric)).

返回

# A tibble: 2 x 5
      a b         c     d e    
  <dbl> <chr> <dbl> <dbl> <lgl>
1     1 Fred      1     1 NA    
2     2 Kevin     2     3 NA   

数据

data <- tibble(a = c("1", "2"), 
               b = c("Fred", "Kevin"), 
               c = 1:2, 
               d = c("1", "3"), 
               e = c(NA, NA))
于 2021-07-04T17:31:35.357 回答
1

它并没有严格按照您的要求做,但是您可以使用阅读器guess_parserparse_guess功能。有关更多详细信息,请参阅https://readr.tidyverse.org/reference/parse_guess.html

在你的情况下,你可以这样做:

df %>% mutate(across(everything(),parse_guess))

这将解析所有列。或者仅用于解析列是否为数字:

parse_guess_numeric <- function (x){
    if (guess_parser(x, guess_integer=FALSE)=="double"){
        as.numeric(x)
    } else {
        x
    }

}

df %>% mutate(across(everything(),parse_guess_numeric))
于 2021-07-04T17:32:42.077 回答
1

有很多方法可以解决这个问题:使用type.convertor type_convertfrom readr

type.convert(df, as.is = TRUE)
# A tibble: 2 x 3
      a b         c
  <int> <chr> <int>
1     1 Fred      1
2     2 Kevin     2


readr::type_convert(df)

-- Column specification ---------------------------------------------------------------------
cols(
  a = col_double(),
  b = col_character()
)

# A tibble: 2 x 3
      a b         c
  <dbl> <chr> <int>
1     1 Fred      1
2     2 Kevin     2
于 2021-07-04T17:43:14.470 回答
0
library(tidyverse)
df <- tibble(a = c("1", "2"), b = c("Fred", "Kevin"), c = 1:2, d = c(NA, NA))
fltr <- names(df)[map_chr(df, guess_parser) == "double"]
mutate(df, across(all_of(fltr), as.numeric))
#> # A tibble: 2 x 4
#>       a b         c d    
#>   <dbl> <chr> <dbl> <lgl>
#> 1     1 Fred      1 NA   
#> 2     2 Kevin     2 NA

reprex 包于 2021-07-04 创建 (v2.0.0 )

于 2021-07-04T17:59:12.897 回答