Changing the column class of data frames using rows

I have a dataframe where all columns have a class character, but many of the columns must have a numeric or integer class. I also have a character vector containing the desired class for each column, for example.

classes <- c("integer", "integer", "numeric", "character", "logical", "numeric", ... )

I am looking for a way to quickly set the class of each column using this classesvector without a loop.

I was hoping this would be a way to make it look like a naming con, for example.

names(df) <- names

where namesis the vector character, or in my case

class(df) <- classes
+4
source share
1 answer

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
+8
source

All Articles