问题
Consider a data.frame with a mix of data types.
For a weird purpose, a user needs to convert all columns to characters. How is it best done? A tidyverse attempt at solution is this:
map(mtcars,as.character) %>% map_df(as.list) %>% View()
c2<-map(mtcars,as.character) %>% map_df(as.list)
when I call str(c2)
it should say a tibble or data.frame with all characters.
The other option would be some parameter settings for write.csv()
or in write_csv()
to achieve the same thing in the resulting file output.
回答1:
You can also use dplyr::mutate_all
.
library(dplyr)
mtcars %>%
mutate_all(as.character)
回答2:
mutate_all
and re-casting the data.frame after lapply
will cause the data.frame's attributes to change. If you need to retain row.names, labels or other attributes associated with the underlying data.frame, try:
x[] <- lapply(x, as.character)
This converts the columns to character class in place, retaining the data.frame's attributes.
Example
x <- mtcars
attr(x, "example") <- "1"
Only in the last case below is the example
attribute retained:
x %>%
mutate_all(as.character) %>%
attributes()
data.frame(lapply(x, as.character)) %>%
attributes()
x[] <- lapply(x, as.character)
attributes(x)
回答3:
This might work, but not sure if it's the best.
df = data.frame(lapply(mtcars, as.character))
str(df)
回答4:
Most efficient way using data.table
-
data.table::setDT(mtcars)
mtcars[, (colnames(mtcars)) := lapply(.SD, as.character), .SDcols = colnames(mtcars)]
Note: You can use this to convert few columns of a data table
to your desired column type.
If we want to convert all columns to character then we can also do something like this-
to_col_type <- function(col_names,type){
get(paste0("as.", type))(dt[[col_names]])
}
mtcars<- rbindlist(list(Map(to_col_type ,colnames(mtcars),"character")))
来源:https://stackoverflow.com/questions/43789278/convert-all-columns-to-characters-in-a-data-frame