0

My data is as follows

 Name  Maths  Science  English  History  German
 Alex  100    98       88       90       89
 Adam  90     100      98       98       98
 James 98     89       90       98       100
 Matt  98     80       100      99       99
 Pat   98     98       98       100      84

Now, I want to add the number of "98" scores by row. How can I do that? I've tried using rowSums but can't seem to get the answer.

Student
  • 107
  • 6

1 Answers1

1

If you just want to get the counts, it's simply rowSums(df == 98).

If you want to add it as a column, then in base R:

df[, "total"] <- rowSums(df == 98)
df
#>    Name Maths Science English History German total
#> 1  Alex   100      98      88      90     89     1
#> 2  Adam    90     100      98      98     98     3
#> 3 James    98      89      90      98    100     2
#> 4  Matt    98      80     100      99     99     1
#> 5   Pat    98      98      98     100     84     3

Or in dplyr, if you prefer:

library(dplyr)

df %>% mutate(total = rowSums(. == 98))
#>    Name Maths Science English History German total
#> 1  Alex   100      98      88      90     89     1
#> 2  Adam    90     100      98      98     98     3
#> 3 James    98      89      90      98    100     2
#> 4  Matt    98      80     100      99     99     1
#> 5   Pat    98      98      98     100     84     3

Here's the data:

txt <- " Name  Maths  Science  English  History  German
 Alex  100    98       88       90       89
 Adam  90     100      98       98       98
 James 98     89       90       98       100
 Matt  98     80       100      99       99
 Pat   98     98       98       100      84"

df <- read.table(text = txt, header = TRUE)

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

MSR
  • 2,731
  • 1
  • 14
  • 24
  • Would the same code work if the variables were characters rather than numeric or integers? – Student Dec 14 '19 at 11:25
  • I actually thought no, but I just tested, and it seems fine. If you have issues, edit your post with a `dput` of a small sample of your data, and I'll take a look. – MSR Dec 14 '19 at 11:39