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.
To convert all columns of the data frame into the character we use apply() function with as. character parameter. The lapply() function applies the given function to the provided data frame.
To convert columns of an R data frame from integer to numeric we can use lapply function. For example, if we have a data frame df that contains all integer columns then we can use the code lapply(df,as. numeric) to convert all of the columns data type into numeric data type.
To convert the data type of all columns from integer to factor, we can use lapply function with factor function.
In R, you can convert multiple numeric variables to factor using lapply function. The lapply function is a part of apply family of functions. They perform multiple iterations (loops) in R. In R, categorical variables need to be set as factor variables.
EDIT: 2021-03-01
Beginning with dplyr 1.0.0, the _all()
function variants are superceded. The new way to accomplish this is using the new across()
function.
library(dplyr) mtcars %>% mutate(across(everything(), as.character))
With across()
, we choose the set of columns we want to modify using tidyselect helpers (here we use everything()
to choose all columns), and then specify the function we want to apply to each of the selected columns. In this case, that is as.character()
.
Original answer:
You can also use dplyr::mutate_all
.
library(dplyr) mtcars %>% mutate_all(as.character)
In base R:
x[] <- lapply(x, as.character)
This converts the columns to character class in place, retaining the data.frame's attributes. A call to data.frame()
would cause them to be lost.
Attribute preservation using dplyr: Attributes seem to be preserved during dplyr::mutate(across(everything(), as.character))
. Previously they were destroyed by dplyr::mutate_all
.
Example
x <- mtcars attr(x, "example") <- "1"
In the second case below, the example
attribute is retained:
# Destroys attributes data.frame(lapply(x, as.character)) %>% attributes() # Preserves attributes x[] <- lapply(x, as.character) attributes(x)
This might work, but not sure if it's the best.
df = data.frame(lapply(mtcars, as.character))
str(df)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With