如何对数据框指定列单独应用readr::type_convert函数?
Great question! The issue with your initial attempts using map_at and sapply with readr::type_convert is that this function is designed to operate on entire data frames, not individual columns. When you pass a single column (a vector) to it, it throws an error because it expects a data frame input.
Here are a few clean ways to selectively apply type conversion to specific columns while keeping others as character:
1. Use dplyr::across with base::type.convert (simplest for most cases)
Base R's type.convert works on individual vectors (unlike readr::type_convert), so pairing it with dplyr::across lets you target specific columns directly in your data frame pipeline:
library(tidyverse) # Original data frame df <- data.frame(A = letters[1:10], B = as.character(1:10), C = as.character(1:10)) # Convert only column B df_converted <- df %>% mutate(across(B, type.convert)) # Check the result str(df_converted) # 'data.frame': 10 obs. of 3 variables: # $ A: chr "a" "b" "c" "d" ... # $ B: int 1 2 3 4 5 6 7 8 9 10 # $ C: chr "1" "2" "3" "4" ...
For multiple columns, just pass a vector of column names or a selection helper (like starts_with("B")):
# Convert columns B and C df %>% mutate(across(c(B, C), type.convert))
2. Use purrr::map_at with base::type.convert
If you prefer purrr-style mapping, you can apply type.convert to selected columns and bind the results back into a data frame:
df %>% map_at("B", type.convert) %>% bind_cols()
3. Use readr::type_convert with explicit column types
If you want to stick with readr::type_convert, you can define a column type specification that keeps non-target columns as character. This is useful if you need fine-grained control over the exact types:
# Define which columns to convert (others stay character) col_spec <- cols( A = col_character(), B = col_guess(), # Let readr guess the type of B C = col_character() ) df %>% type_convert(col_types = col_spec)
For large data frames with many columns, you can dynamically build the specification to avoid listing every column:
cols_to_convert <- c("B") col_spec <- cols(.default = col_character()) # Default all to character col_spec[cols_to_convert] <- list(col_guess()) # Override target columns df %>% type_convert(col_types = col_spec)
Each of these approaches will let you convert only the columns you want, while preserving the character type of the rest.
内容的提问来源于stack exchange,提问作者simoncolumbus

