如何分组并依靠r中的每一列

时间:2018-06-14 07:51:02

标签: r

我在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

我想在按Positive

分组的每个列中计算Village.Name

我想要的数据框是

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

我怎样才能在R?

中完成

1 个答案:

答案 0 :(得分:3)

我们可以summarise_all使用一个组来获取每列的sum逻辑向量(.== "Positive"

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
相关问题