【问题标题】:filling a cell with the sum of 2 other cells in R用R中其他2个单元格的总和填充一个单元格
【发布时间】:2016-05-19 03:57:03
【问题描述】:

我需要用多个其他单元格的总和填充一个单元格。 例如(在名为“a”的表中):

for(i on 1:nrows_data){
   if(a[i,"Column 1"]=="yes"){
      a[i,"Column 4"]=a[i,"Column 2"]+a[i,"Column 3"]
   }
}

引用单元格中的值都是数字(我检查过)。如果我这样做,我会收到此错误:

[tmp, i, "Alpha", value = numeric(0)) 中的错误:
替换的长度为零

任何帮助将不胜感激。我的目标是获得所需单元格中显示的引用单元格中包含的两个数值的总和。

【问题讨论】:

  • "Column 4" 是否已经存在?如果没有,如果你的条件不满足,你想放什么?你应该分享一些你的数据,像dput(head(a)) 这样的东西会让一切都清楚。
  • 可能你想要a[, "Column 4"] = ifelse(a[, "Column 1"] == 'yes', a[, 'Column 2'] + a[, 'Column 3'], NA),(当第一列不是"yes"时输入缺失值。
  • 嗨,Noah,您能否告诉我们您的数据 a 是什么样的?有一个reproducible example 会有所帮助

标签: r loops sum


【解决方案1】:

欢迎来到 SO,放置一个简单的可重现示例来帮助我们了解您的问题总是有帮助的。我为你做了一个假的小数据集。这是与您的格式类似的解决方案,也是避免循环的更简单替代方案。

## Typically good notation in R is no spaces in variable names
col_1 <- c("yes","no","yes","yes","no")
col_2 <- c(1,4,2,5,6)
col_3 <- c(9,2,8,5,2)
a <- data.frame(col_1, col_2, col_3)

## This works, small fix 
for(i in 1:nrow(a)){ ## note "in" instead of "on", and you can calculate nrow() right in here, dont have to do it ahead of time.
   if(a[i,"col_1"]=="yes"){
      a[i,"col_4"]=a[i,"col_2"]+a[i,"col_3"]
   }
}

## this works, easy one-liner
## Into column named col_4, for each row if col_1 = "yes", put col_2+col_4 into that cell, otherwise put NA
a$col_4 <- ifelse(a$col_1=="yes",a$col_2+a$col_3,NA)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-12
    • 1970-01-01
    • 2017-09-03
    • 2014-09-13
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    相关资源
    最近更新 更多