1

I have a data frame along the lines of this:

> DF <- data.frame(V1=c("Yes", "Yes", "No"), V2=c("Yes", "No", "No"), V3=c("Yes", "Yes", "No"))
   V1  V2  V3
1 Yes Yes Yes
2 Yes  No Yes
3  No  No  No

No I would like to use something along the line of mutate to count the instances of "Yes" in each row to get something like this:

   V1  V2  V3 CountYes
1 Yes Yes Yes        3
2 Yes  No Yes        2
3  No  No  No        0

Is there an easy way to do it? I am sadly out of ideas.

Thanks and BW, Jan

Jan
  • 53
  • 8

3 Answers3

2

We can use rowSums on a logical matrix

DF$CountYes <- rowSums(DF == 'Yes')
DF$CountYes
#[1] 3 2 0
akrun
  • 874,273
  • 37
  • 540
  • 662
2

That's an overkill, but since you've tagged this with dplyr:

library(dplyr)

DF %>%
  rowwise %>%
  mutate(CountYes = sum(c_across() == 'Yes'))

Output:

# A tibble: 3 x 4
# Rowwise: 
  V1    V2    V3    CountYes
  <fct> <fct> <fct>    <int>
1 Yes   Yes   Yes          3
2 Yes   No    Yes          2
3 No    No    No           0
arg0naut91
  • 14,574
  • 2
  • 17
  • 38
  • 1
    Thank you! Akruns answer worked, but I will keep your methods in mind. They'll probably come in handy soon^^ – Jan Aug 13 '20 at 21:06
2

Another base R option (but not as simple as rowSums by @akrun)

DF$CountYes <- table(stack(data.frame(t(DF))))["Yes",]

which gives

> DF
   V1  V2  V3 CountYes
1 Yes Yes Yes        3
2 Yes  No Yes        2
3  No  No  No        0
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81