Search code examples
rsumdata.table

Creating a new column that has the sum of multiple columns per row using data.table in R


I have a data.table in R that's shown below:

enter image description here

I want to add a column that represents the sum of ace, bb, and statin for every row. So for the rows shown above, the new column would have the following values: 2,1,2,1,2

The name of the table above is adherence, I tried the following code to add the sum:

adherence[, total := sum(ace,bb,statin)]

but instead of calculating the sum per row, it calculates the sum of all three columns and gives me the table below:

enter image description here

How do I get the sum of the three columns per row?


Solution

  • Another solution. (Note that if any row contains a missing value, the row sum would be missing).

    library(data.table)
    
    adherence[, total := ace + bb + statin]