1

I want to go through all variables of my dataset and detect all "yes" then put their number per individual in a new variable "n_yes"

mydata<-data.frame(
  
  aa=c("yes","no",NA,"yes",NA),
  bb=c("no","yes",NA,"unknown",NA),
  klm=c("no","no",NA,"yes",NA),
  ncv=c("no","no",NA,"no",NA),
  d3d=c(NA,NA,NA,NA,NA)
    )

I want to get such a table below:

    aa      bb  klm  ncv d3d n_yes
1  yes      no   no   no  NA     1
2   no     yes   no   no  NA     1
3 <NA>    <NA> <NA> <NA>  NA     0
4  yes unknown  yes   no  NA     2
5 <NA>    <NA> <NA> <NA>  NA     0
Seydou GORO
  • 1,147
  • 7
  • 13
  • 1
    Does this answer your question? [Counting number of instances of a condition per row R](https://stackoverflow.com/questions/32618583/counting-number-of-instances-of-a-condition-per-row-r) – litriv Apr 04 '22 at 14:37

1 Answers1

3

Here is a one-liner:

rowSums(mydata == "yes", na.rm = TRUE)
#[1] 1 1 0 2 0

Or, if you want to create a new column with these results,

mydata$n_yes <- rowSums(mydata == "yes", na.rm = TRUE)
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66