how to sum the data

halo,
can someone help me, i have an example of my data. like this

#> Resp A B C D E F G
#> 0001 3 1 2 2 5 4 1
#> 0002 2 2 5 2 3 1 4
#> 0003 3 4 2 3 5 1 2
#> 0004 4 1 1 2 1 3 5
#> 0005 5 3 2 1 1 4 3

My question is, what code should I use to sum tha data ABCDEFG on each Resp?
example:
0001 = 3+1+2+2+5+4+1 = 18
thank you :slight_smile:

Hi,

For future reference, it would make it easier for people to help you if you provided your data sample in a format that they could easily copy and paste into R, for example the output from dput, eg dput(DF) or dput(head(DF)).

There will be a stack of ways to do this, here are a couple with or without using the tidyverse:

library(tidyverse)

JJ <- structure(list(Resp = c("0001", "0002", "0003", "0004", "0005"
), A = c(3L, 2L, 3L, 4L, 5L), B = c(1L, 2L, 4L, 1L, 3L), C = c(2L,
5L, 2L, 1L, 2L), D = c(2L, 2L, 3L, 2L, 1L), E = c(5L, 3L, 5L,
1L, 1L), F = c(4L, 1L, 1L, 3L, 4L), G = c(1L, 4L, 2L, 5L, 3L)), class = "data.frame", row.names = c(NA,
-5L))

# tidyverse solution
JJ %>% gather(key = 'var', value = 'value', -Resp) %>%
       group_by(Resp) %>%
       summarise(sum=sum(value))
#> # A tibble: 5 x 2
#>   Resp    sum
#>   <chr> <int>
#> 1 0001     18
#> 2 0002     19
#> 3 0003     20
#> 4 0004     17
#> 5 0005     19

# non-tidyverse solution
rowSums(JJ[, names(JJ) %in% LETTERS[1:7]])
#> [1] 18 19 20 17 19

Created on 2019-04-04 by the reprex package (v0.2.1)

Ron.

4 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.