Search code examples
rtidyverse

Row Wise Addition in R


I have this data frame called "game":

            all_d tit_for_tat perm_retal random joss tester tit_for_two
all_d         200         199        199    102  199    198         198
tit_for_tat   204         600        600    483  215    599         600
perm_retal    204         600        600    113  208    202         600
random        579         440        608    445  481    429         381
joss          204         250        245    417  201    251         538
tester        208         599        207    453  225    598         303
tit_for_two   208         600        600    610  639    798         600
score         1807        3288       3059   2623 2168   3075        3220

I would like to get the sum by adding each row in an efficient manner, I was able to do it with:

game %>% rowwise() %>% mutate(score = sum(c(all_d,tit_for_tat,perm_retal,random,joss,tester,tit_for_two)))

to get this table:

  all_d tit_for_tat perm_retal random  joss tester tit_for_two score
  <dbl>       <dbl>      <dbl>  <dbl> <dbl>  <dbl>       <dbl> <dbl>
1   200         199        199    102   199    198         198  1295
2   204         600        600    483   215    599         600  3301
3   204         600        600    113   208    202         600  2527
4   579         440        608    445   481    429         381  3363
5   204         250        245    417   201    251         538  2106
6   208         599        207    453   225    598         303  2593
7   208         600        600    610   639    798         600  4055
8  1807        3288       3059   2623  2168   3075        3220 19240

The question is, say I had a lot more rows to so summarise, is there a better way of adding all the row values to save me the time of typing all the column names?


Solution

  • If it is just across all columns, then you can just use rowSums.

    library(dplyr)
    
    df %>% 
      mutate(score = rowSums(df))
    

    Or in base R

    df$score <- rowSums(df)
    

    Output

      all_d tit_for_tat perm_retal random joss tester tit_for_two score
    1   200         199        199    102  199    198         198  1295
    2   204         600        600    483  215    599         600  3301
    3   204         600        600    113  208    202         600  2527
    4   579         440        608    445  481    429         381  3363
    5   204         250        245    417  201    251         538  2106
    6   208         599        207    453  225    598         303  2593
    7   208         600        600    610  639    798         600  4055
    8  1807        3288       3059   2623 2168   3075        3220 19240