首页 > 解决方案 > 根据R中的数字和整数类型将数据帧分成两部分

问题描述

我想将数据框拆分为df1df2基于数据类型numericinteger.

df1和将df2分别包含"bmi", "age", "cal", "pro""male", "urban"

sapply(df, class)

出去:

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

str(df)

出去:

'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 ...

我怎么能在 R 中做到这一点?谢谢你。

我尝试使用unlist(lapply(df, is.numeric)),但它不能区分numericinteger

更新:

使用下面的代码,我得到一个数据框,但它不是 的子集df,另一个问题是包含的interger列:

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

出去:

在此处输入图像描述

标签: rdataframe

解决方案


以下代码有效,非常感谢@A5C1D2H2I1M1N2O1R2T1 和@Ronak Shah。

out <- split.default(df, sapply(df, class))
names(out) <- paste0('df', seq_along(out))
names(out) 
list2env(out, .GlobalEnv)

推荐阅读