HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

More concise way to sum elements of columns in R

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
elementscolumnsmorewayconcisesum

Problem

Is there a more efficient/concise way to add the elements of these columns? Basically the D-# codes are error code for documents, and the Q# codes are classes of error.

##Summary columns##
errorarray$Q1 <- errorarray$"D-03" + errorarray$"D-06" + errorarray$"D-07" + errorarray$"D-14" + errorarray$"D-15" + errorarray$"D-16"   
errorarray$Q2 <- errorarray$"D-01" + errorarray$"D-02" + errorarray$"D-04" + errorarray$"D-05"
errorarray$Q3 <- errorarray$"D-08" + errorarray$"D-09" + errorarray$"D-10" + errorarray$"D-11" + errorarray$"D-12" + errorarray$"D-13" + errorarray$"D-17" + errorarray$"D-18" +  errorarray$"D-19"


Thank you

Solution

Assuming your data are numeric and your columns are ordered by D-#, the following approaches should work:

Using apply:

errorarray$Q1 <- apply(errorarray[, c(3, 6, 7, 14:16)], 1, sum) # using col indices
errorarray$Q1 <- apply(errorarray[c("D-03", "D-06", "D-07", "D-15", "D-16")], 1, sum) # using column names


Using rowSums:

errorarray$Q1 <- rowSums(errorarray[, c(3, 6, 7, 14:16)]) # using indices
errorarray$Q1 <- rowSums(errorarray[c("D-03", "D-06", "D-07", "D-15", "D-16")]) # using column names


Note you can use ":" to denote the start and end of a number of consecutive columns.

Code Snippets

errorarray$Q1 <- apply(errorarray[, c(3, 6, 7, 14:16)], 1, sum) # using col indices
errorarray$Q1 <- apply(errorarray[c("D-03", "D-06", "D-07", "D-15", "D-16")], 1, sum) # using column names
errorarray$Q1 <- rowSums(errorarray[, c(3, 6, 7, 14:16)]) # using indices
errorarray$Q1 <- rowSums(errorarray[c("D-03", "D-06", "D-07", "D-15", "D-16")]) # using column names

Context

StackExchange Code Review Q#157249, answer score: 6

Revisions (0)

No revisions yet.