Reputation: 79
I imagine there is a simple function for this but I can't seem to find it. I have five columns within a larger data frame that I want to add to get a single sum. Here's what I did, but I am wondering if there is a much simpler way to get the same result:
count <- subset(NAMEOFDATA, select=c(COL1,COL2,COL3,COL4,COL5))
colcount <- as.data.frame(colSums(count))
colSums(colcount)
Upvotes: 1
Views: 152
Reputation: 263471
The sum function should do that:
sum(count)
Unlike "+" which is vectorized, sum
will "collapse" its arguments and it will accept a data.frame argument. If some of the arguments are logical, then TRUE==1 and FALSE==0 for purposes of summation, which makes the construction sum(is.na(x))
possibly useful.
Upvotes: 3
Reputation: 72769
Always easier with a reproducible example, but here's an attempt:
apply( NAMEOFDATA[,paste0("COL",seq(5))], 1, sum )
Upvotes: 0