I have a dataframe where all the columns have the character
class but many of the columns should be of numeric or integer class. I also have a character vector containing the desired class for each column e.g.
classes <- c("integer", "integer", "numeric", "character", "logical", "numeric", ... )
I am looking for a way to set the class of each column quickly using this classes
vector without looping.
I was hoping there would be a way to do this similar to naming, e.g.
names(df) <- names
where names
is a character
vector, or in my case
class(df) <- classes
You can change data types using as. * where * is the datatype to change to, the other way is using class(). class(df$var) = "Numeric".
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.
If you want to change the data type for all columns in the DataFrame to the string type, you can use df. applymap(str) or df. astype(str) methods.
Use Map
:
df <- data.frame(V1=letters[1:3],
V2=c("1","2","3"),
V3=c("1.1","2.2","3.3"),stringsAsFactors=FALSE)
classes <- c("character","integer","numeric")
str(df)
#'data.frame': 3 obs. of 3 variables:
# $ V1: chr "a" "b" "c"
# $ V2: chr "1" "2" "3"
# $ V3: chr "1.1" "2.2" "3.3"
df[] <- Map(`class<-`, df, classes)
str(df)
#'data.frame': 3 obs. of 3 variables:
# $ V1: chr "a" "b" "c"
# $ V2: int 1 2 3
# $ V3: num 1.1 2.2 3.3
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