1

I need to sum columns of a table that have a names starting with a particular string.

An example table might be:

tbl<-data.frame(num1=c(3,2,9), num2=c(3,2,9),n3=c(3,2,9),char1=c('a', 'b', 'c'))

I get the list of columns (in this example I wrote only 2, but the real case has more tan 20).

a<-colnames(tbl)[grep('num', colnames(tbl))]

I tried with

sum(tbl[,a])

But I get only one number with the total sum of the elements in both vectors.

What I need is the result of:

tbl$num1+ tbl$num2
oguz ismail
  • 1
  • 16
  • 47
  • 69
GabyLP
  • 3,649
  • 7
  • 45
  • 66

1 Answers1

0

We can either use Reduce

 Reduce(`+`, tbl[a])

Or rowSums. The rowSums also has the option of removing the NA elements with na.rm=TRUE.

rowSums(tbl[a])
akrun
  • 874,273
  • 37
  • 540
  • 662