'how to go through all my variables and detect a characteristic
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
Solution 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rui Barradas |