How to count the number of values in R

时间:2018-03-22 23:34:16

标签: r count

I got several columns in my dataset, which was shown like below:

ID...Var1  Var2  Var3  Var4  Var5  Var6...
1... Yes   No    Yes    No    No   Yes...
2... No    No    No     No    No    No...
3... Yes  Yes   Yes    Yes   No    Yes...
4... No    No    No     No    No    No...
5... No   Yes    Yes    No    No   Yes...
6... No    No    Yes    No    No   Yes...
7... Yes  Yes    No     No    No    No...

And I want to count how many "Yes" for each ID person in these 6 variables, which means I want add the column like this:

ID...Var1  Var2  Var3  Var4  Var5  Var6  Count
1... Yes   No    Yes    No    No   Yes     3
2... No    No    No     No    No    No     0
3... Yes  Yes   Yes    Yes   No    Yes     5
4... No    No    No     No    No    No     0
5... No   Yes    Yes    No    No   Yes     3
6... No    No    Yes    No    No   Yes     2
7... Yes  Yes    No     No    No    No     2

And I was using R to do the data management, can you guys provide me some guide or R syntax help?

1 个答案:

答案 0 :(得分:1)

Here's a smaller, reproducible example & solution of your problem. (Future hint: make sure to include an actual easy to use, reproducible sample of your data)

df <- data.frame(v1 = c("Yes", "Yes", "Yes", "No"),
                 v2 = c("No", "Yes", "No", "No"),
                 v3 = c("Yes", "Yes", "No", "No"), stringsAsFactors = FALSE)

df$count <- rowSums(df[c(1,3)] == "Yes")

df

   v1  v2  v3 count
1 Yes  No Yes     2
2 Yes Yes Yes     2
3 Yes  No  No     1
4  No  No  No     0