用R中的2个其他单元的总和填充单元格

时间:2016-05-18 19:38:53

标签: r loops sum

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

Xamarin.Forms.Forms.ViewInitialized += (object sender, Xamarin.Forms.ViewInitializedEventArgs e) => {
   if (!string.IsNullOrWhiteSpace (e.View.AutomationId)) {
      e.NativeView.ContentDescription = e.View.AutomationId;
   }
};

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

  

[。data.frame( tmp ,i,“Alpha”,value = numeric(0))中的错误:
  替换的长度为零

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

1 个答案:

答案 0 :(得分: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)