仅将 readr::type_convert 映射到特定列
Map readr::type_convert to specific columns only
readr::type_convert 猜测数据框中每一列的 class。我想将 type_convert 应用于数据框中的某些列(以将其他列保留为字符)。 MWE:
# A data frame with multiple character columns containing numbers.
df <- data.frame(A = letters[1:10],
B = as.character(1:10),
C = as.character(1:10))
# This works
df %>% type_convert()
Parsed with column specification:
cols(
A = col_character(),
B = col_double(),
C = col_double()
)
A B C
1 a 1 1
2 b 2 2
...
但是,我只想将该函数应用于 B 列(这是一个程式化的示例;可能有多个列要尝试和转换)。我尝试使用 purrr::map_at 以及 sapply,如下所示:
# This does not work
map_at(df, "B", type_convert)
Error in .f(.x[[i]], ...) : is.data.frame(df) is not TRUE
# This does not work
sapply(df["B"], type_convert)
Error in FUN(X[[i]], ...) : is.data.frame(df) is not TRUE
有没有一种方法可以选择性地将 type_convert 应用于数据框的某些列?
编辑: @ekoam 提供了 type_convert 的答案。但是,将此答案应用于许多专栏会很乏味。使用 base::type.convert 函数可能会更好,可以映射:
purrr::map_at(df, "B", type.convert) %>%
bind_cols()
# A tibble: 10 x 3
A B C
<chr> <int> <chr>
1 a 1 1
2 b 2 2
type_convert
好像不支持。我用过几次的一个技巧是使用 select
和 bind_cols
的组合,如下所示。
df %>%
select(B) %>%
type_convert() %>%
bind_cols(df %>% select(-B))
试试这个:
df %>% type_convert(cols(B = "?", C = "?", .default = "c"))
猜B
的类型;任何其他字符列保持原样。棘手的部分是,如果任何列不是字符类型,那么 type_convert
也会保持原样。所以如果你真的必须type_convert
,也许你必须先将所有列转换为字符。
readr::type_convert 猜测数据框中每一列的 class。我想将 type_convert 应用于数据框中的某些列(以将其他列保留为字符)。 MWE:
# A data frame with multiple character columns containing numbers.
df <- data.frame(A = letters[1:10],
B = as.character(1:10),
C = as.character(1:10))
# This works
df %>% type_convert()
Parsed with column specification:
cols(
A = col_character(),
B = col_double(),
C = col_double()
)
A B C
1 a 1 1
2 b 2 2
...
但是,我只想将该函数应用于 B 列(这是一个程式化的示例;可能有多个列要尝试和转换)。我尝试使用 purrr::map_at 以及 sapply,如下所示:
# This does not work
map_at(df, "B", type_convert)
Error in .f(.x[[i]], ...) : is.data.frame(df) is not TRUE
# This does not work
sapply(df["B"], type_convert)
Error in FUN(X[[i]], ...) : is.data.frame(df) is not TRUE
有没有一种方法可以选择性地将 type_convert 应用于数据框的某些列?
编辑: @ekoam 提供了 type_convert 的答案。但是,将此答案应用于许多专栏会很乏味。使用 base::type.convert 函数可能会更好,可以映射:
purrr::map_at(df, "B", type.convert) %>%
bind_cols()
# A tibble: 10 x 3
A B C
<chr> <int> <chr>
1 a 1 1
2 b 2 2
type_convert
好像不支持。我用过几次的一个技巧是使用 select
和 bind_cols
的组合,如下所示。
df %>%
select(B) %>%
type_convert() %>%
bind_cols(df %>% select(-B))
试试这个:
df %>% type_convert(cols(B = "?", C = "?", .default = "c"))
猜B
的类型;任何其他字符列保持原样。棘手的部分是,如果任何列不是字符类型,那么 type_convert
也会保持原样。所以如果你真的必须type_convert
,也许你必须先将所有列转换为字符。