Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing class of data frame columns using strings

Tags:

r

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
like image 445
mattdevlin Avatar asked Dec 12 '14 02:12

mattdevlin


People also ask

How do I change the column type in R?

You can change data types using as. * where * is the datatype to change to, the other way is using class(). class(df$var) = "Numeric".

How do I convert a column to a character in a DataFrame in R?

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.

How do you convert a whole DataFrame to a string in Python?

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.


1 Answers

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
like image 199
thelatemail Avatar answered Oct 09 '22 06:10

thelatemail