0

I need to fill a cell with the sum of multiple other cells. For example (in a table called '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"]
   }
}

Where the values in the referenced cells are all numeric (I checked). If I do this I get this error:

Error in [<-.data.frame(tmp, i, "Alpha", value = numeric(0)) :
replacement has length zero

Any help would be greatly appreciated. My goal is to get the sum of the two numerical values contained in referenced cells displayed in the desired cell.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
Noah
  • 11
  • 5
  • Does `"Column 4"` already exist? If not, what do you want to put there if your condition isn't met? You should share a bit of your data, something like `dput(head(a))` would make everything clear. – Gregor Thomas May 18 '16 at 19:48
  • Probably you want `a[, "Column 4"] = ifelse(a[, "Column 1"] == 'yes', a[, 'Column 2'] + a[, 'Column 3'], NA)`, (to put missing values when the first column isn't `"yes"`. – Gregor Thomas May 18 '16 at 19:51
  • 2
    Hi Noah, could you please give us an idea of what your data `a` looks like? It would help to have a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – BarkleyBG May 18 '16 at 19:52

1 Answers1

1

welcome to SO, its ALWAYS helpful to put a simple reproducible example to help us see your problem. I made a fake little data set for you. Here is a solution similar to your format, and an easier alternative that avoids the loop.

## 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)
TBSRounder
  • 348
  • 1
  • 9