-3

I have a following dataframe in r

   Introvert     Extrovert    Biased     Village.Name
    Positive      Negative    Negative     ABC
    Negative      Negative    Negative     ABC
    Negative      Positive    Positive     ABC
    Positive      Negative    Negative     DEF
    Negative      Positive    Positive     DEF
    Negative      Positive    Positive     DEF

I want to count Positive in every columns grouped by Village.Name

My desired dataframe would be

    Village.Name     Introvert    Extrovert    Biased
     ABC                1            1           1
     DEF                1            2           2

How can I do it in R?

Neil
  • 7,295
  • 20
  • 74
  • 127

1 Answers1

4

We can use a group by summarise_all to get the sum of logical vector (.== "Positive") for each of the columns

library(dplyr)
df1 %>% 
    group_by(Village.Name) %>%
    summarise_all(funs(sum(.=="Positive")))
# A tibble: 2 x 4
#  Village.Name Introvert Extrovert Biased
#  <chr>            <int>     <int>  <int>
#1 ABC                  1         1      1
#2 DEF                  1         2      2
akrun
  • 789,025
  • 32
  • 460
  • 575