1

I want to split a dataframe into df1 and df2 based on data type numeric and integer.

The df1 and df2 will respectively contain "bmi", "age", "cal", "pro" and "male", "urban".

sapply(df, class)

Out:

      bmi       age       cal       pro      male 
"numeric" "numeric" "numeric" "numeric" "integer" 
    urban 
"integer" 

str(df)

Out:

'data.frame':   4825 obs. of  6 variables:
 $ bmi  : num  24.7 25.3 22.8 21.7 24.2 ...
 $ age  : num  37.5 36.5 37 36.9 40 ...
 $ cal  : num  6.31 1.84 3.87 2.67 1.59 ...
 $ pro  : num  13.57 13.43 9.57 12.51 11.65 ...
 $ male : int  1 0 1 0 1 0 0 1 1 0 ...
 $ urban: int  1 1 1 1 1 1 1 1 1 1 ...

How can I do that in R? Thank you.

I try with unlist(lapply(df, is.numeric)), but it doesn't distingue numeric and integer.

Update:

With the code below I get a dataframe but it's not a subset of df, another problem is interger columns included:

numeric <- which(sapply(df,is.numeric))
df1 <- as.data.frame(numeric)
print(df1) 

Out:

enter image description here

8
  • split.default(df, sapply(df, class)). Use list2env if you want to get it out of a list and into your global environment. Commented Apr 1, 2020 at 6:15
  • Thank you but how to set df1 and df2? Commented Apr 1, 2020 at 6:19
  • Using list2env(your_list, .GlobalEnv). You'll probably want to rename the items in the list before you do that. Commented Apr 1, 2020 at 6:23
  • 1
    1) out <- split.default(df, sapply(df, class)). 2) names(out) <- paste0('df', seq_along(out)) 3) list2env(out, .GlobalEnv) Commented Apr 1, 2020 at 6:29
  • 1
    @A5C1D2H2I1M1N2O1R2T1 you should probably add it as an answer. Can't find an exact dupe to split based on class. Commented Apr 1, 2020 at 6:33

1 Answer 1

0

The following code works, many thanks to @A5C1D2H2I1M1N2O1R2T1 and @Ronak Shah.

out <- split.default(df, sapply(df, class))
names(out) <- paste0('df', seq_along(out))
names(out) 
list2env(out, .GlobalEnv)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.