【问题标题】:In R, How do you extract columns when you don't know how many columns there are in all datasets?在 R 中,当您不知道所有数据集中有多少列时,如何提取列?
【发布时间】:2021-03-19 23:12:17
【问题描述】:

我有一个包含 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

版本 _
平台 x86_64-apple-darwin15.6.0
拱 x86_64
操作系统 darwin15.6.0
系统 x86_64、darwin15.6.0
状态
专业 3
次要 5.3
2019 年
03月
第 11 天
svn 版本 76217
语言 R
version.string R 版本 3.5.3 (2019-03-11) 绰号大真理

谢谢!!

【问题讨论】:

  • 数据框中的列数使用您似乎已正确使用的length 函数返回。您的循环中唯一缺少的似乎是summaryofsums 的初始化。您应该始终发布任何错误消息的完整文本。那么你的问题到底是什么?

标签: r sum extract multiple-columns


【解决方案1】:

使用sapply

sapply(locs, function(df) {
  newdf <- df[, colSums(df!= 0, na.rm = TRUE) > 0]
  colSums(newdf[,9:ncol(newdf)], na.rm = TRUE)  
}) -> result

result

【讨论】:

    【解决方案2】:

    我注意到的第一件事是,您正在列表上执行 1:length(),但没有调用该列表中的项目,例如,以您想要的方式:

    for(i in 1:length(locs)){
     locs[[i]] #where this is now df in your code
     ....
    }
    

    我认为,更简单的方法是:

     # Create your (I assume) variable to hold your sums
     0 -> summaryofsums
     
     # Loop through each dataframe and get the sum of everything after 9th column
     # This will produce a list with each entry the sum of each column after 9 per
     # dataframe
     for(df in locs){
      df[, colSums(df) > 0] -> newdf
      sum(colSums(newdf[, 9:ncol(newdf)])) + summaryofsums -> summaryofsums
      }
      
    

    这将简单地创建一个变量summaryofsums,它是所有数据集的第 9 列之后所有列中所有值的总和。

    【讨论】:

    • 谢谢!我收到括号错误? “意外的 '}' 在:“summaryofsums
    • 已修复!抱歉 - 缺少“)”。
    猜你喜欢
    • 2021-08-05
    • 2014-04-11
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 2023-02-10
    • 1970-01-01
    • 2017-05-20
    相关资源
    最近更新 更多