adrianmcmenamin
adrianmcmenamin

Reputation: 1129

How to sum certain columns row-by-row in R?

I have a dataframe that looks like this (with values for all Threads as the frame progresses):

head(icdata)
     Count Thread1 Thread2 Thread3 Thread4 Thread5 Thread6 Thread7 Thread8 
1  8543034  555724      NA      NA      NA      NA      NA      NA      NA
2 26632195  730156      NA      NA      NA      NA      NA      NA      NA
3 46332821  730679      NA      NA      NA      NA      NA      NA      NA
4 47491531   22694   16715      NA      NA      NA      NA      NA      NA
5 48939781   62418  114842      NA      NA      NA      NA      NA      NA
6 50397031   63560   38147      NA      NA      NA      NA      NA      NA

I'd like to plot Count against the sum of the various threads, but cannot work out just how to do it - eg the NA values seem to cause me problems in just summing the row. Sorry to ask such a basic question but how can I do this?

(Additionally, I'd like to be able to normalise this total against the difference in the Counts, but that is less essential)

Upvotes: 0

Views: 765

Answers (1)

nico
nico

Reputation: 51640

Use rowSums to sum the values in the various threads. The na.rm parameters takes care of NAs. Furthermore, you want to exclude the first column from the sum so:

thread.sum <- rowSums(icdata[,-1], na.rm=TRUE)
plot(icdata[,1], thread.sum)

Upvotes: 3

Related Questions