Elizabeth Smith Elizabeth Smith - 1 year ago 91
R Question

How to separate a dataframe in 2 different ones based on variable datatypes in R

I have a dataframe with numeric variables and categorical factors and i want to separate the dataframe into 2: one with the numeric variables and one with the categorical factors.I am new to R and i am lost.I have tried the split function but i can't work it out.I tried using for loops for checking the variables with is.factor but nothing seems to work!Please help!

Answer Source

As there are only two types ('numeric' and 'factor'), we get the class of column types by looping through the dataset columns (sapply(df1, class) ) and use that to split the data.frame into a list of 'data.frame's.

lst <- split.default(df1, sapply(df1, class))


df1 <- data.frame(Col1 = LETTERS[1:5], Col2 = as.numeric(1:5), Col3= rnorm(5))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download