Search code examples
rrowsum

In R, how to do rowsums for columns with negative and positive integers?


I'm trying to sum 4 columns, some of which have negative values. I get an error message when I do so:

Error in .subset(x, j) : only 0's may be mixed with negative subscripts

Is there a way to overcome this and get the sum? I read what's been written about the error showing up but couldn't figure out a solution

Here is my code:

calculation1 <- (rawdata$Concat1 * 12 / rawdata$Size) 
calculation2 <- rawdata$Concat2 * 12 / rawdata$Size
calculation3 <- rawdata$Concat3 * 12 / rawdata$Size
calculation4 <- rawdata$Concat4 * 12 / rawdata$Size

rawdata$Cost <- rowSums(rawdata[,c(calculation1, calculation2, calculation3, 
calculation4)], na.rm=TRUE)

Solution

  • The objects 'calculation' are not column names. We can get those objects in to a list with mget, cbind and do the rowSums

    rawdata$Cost <- rowSums(do.call(cbind,
           mget(ls(pattern = '^calculation\\d+$'))), na.rm = TRUE)
    

    Or use cbind instead of c to convert to a matrix (or data.frame)

    rowSums(cbind(calculation1, calculation2, calculation3,  
           calculation4), na.rm = TRUE)
    

    Also, instead of creating multiple objects, we could do this simply by

    rowSums(rawdata[paste0('Concat', 1:4)] * 12/rawdata$Size, na.rm = TRUE)