r - 根据R中的数字和整数类型将数据帧分成两部分
问题描述
我想将数据框拆分为df1
并df2
基于数据类型numeric
和integer
.
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))
,但它不能区分numeric
和integer
。
更新:
使用下面的代码,我得到一个数据框,但它不是 的子集df
,另一个问题是包含的interger
列:
numeric <- which(sapply(df,is.numeric))
df1 <- as.data.frame(numeric)
print(df1)
出去:
解决方案
以下代码有效,非常感谢@A5C1D2H2I1M1N2O1R2T1 和@Ronak Shah。
out <- split.default(df, sapply(df, class))
names(out) <- paste0('df', seq_along(out))
names(out)
list2env(out, .GlobalEnv)
推荐阅读
- php - 未找到 Opencart 自定义控制器功能
- ruby - 如何在 Sinatra 中读取 HTTParty 发送的数据
- javascript - 重构对象键以避免重言式
- restler - Restler3 与 Grafana SimpleJson 插件的集成
- spring - 如何在自定义 Spring items.xml 中使用 OOTB 枚举作为属性类型
- git - OkHttp:3.12.x 分支会有发布吗?
- javascript - 替换重复的 document.getElementById
- codeigniter - 如何使用 htaccess 或 codeigniter 在 URL 中添加用户名
- python - Cython 是否将静态字典键编译为其哈希值?
- android - 打开使用 Retrofit2 下载的通知点击文件