r - 在 R 中,当您不知道所有数据集中有多少列时,如何提取列?
问题描述
我有一个包含 52 个数据集的列表,我试图从每个数据集中获取指定数量的列的列总和,并将其导出到一个新的数据框。我知道我想对第 9 列及之后的所有内容求和,但每个数据集的总列数各不相同。(“locs”是我的数据框列表)
这是我尝试使用 for 循环的方法:
summaryofsums <- vector("list",1) #empty vector
for (df in 1:length(locs)){
newdf <- df[, colSums(df!= 0) > 0] #get rid of all columns that have only 0s
newdfsum <- colSums(newdf[,9:length(newdf)])
summaryofsums[i] <- newdfsum
}
我收到以下错误:
Error in colSums(df != 0) :
'x' must be an array of at least two dimensions
version _
platform x86_64-apple-darwin15.6.0
arch x86_64
os darwin15.6.0
system x86_64, darwin15.6.0
status
major 3
minor 5.3
year 2019
month 03
day 11
svn rev 76217
language R
version.string R version 3.5.3 (2019-03 -11) 昵称伟大的真理
谢谢!!
解决方案
使用sapply
:
sapply(locs, function(df) {
newdf <- df[, colSums(df!= 0, na.rm = TRUE) > 0]
colSums(newdf[,9:ncol(newdf)], na.rm = TRUE)
}) -> result
result
推荐阅读
- python-3.x - 你能帮我解决“无法分配给函数调用”的错误吗?
- python - 无法在 AWS Lambda 函数中导入 sqlalchemy
- python-3.x - 在 python 3.7.1 环境中安装 Tensorflow 2.0 后,我需要安装 Keras,还是 Keras 与 TF2.0 捆绑在一起?
- design-patterns - 在构建器模式中,方法“buildpart()”是工厂方法吗?
- angular - 使用订阅与异步管道时来自同一可观察对象的不同结果
- r - 如何在 R 中查找和绘制相关变量?
- performance - 为什么 CUDA 上的 pytorch 训练比 CPU 上的工作慢得多?
- typescript - 当字段名称可以具有多个未知值之一时,如何为 TypeScript 编写接口?
- css - webpack:在 vue 应用程序选择器下限定所有 SCSS
- javascript - Ajax 发送请求两次