简体   繁体   English

如何汇总因子列 R 之间的相等行数?

[英]How summarise count equal rows between factor columns R?

I have followed data example我遵循了数据示例

df <- tibble(var1 = factor(c("a", "a", "a", "b", "b", "c", "c", "c")),
         var2 = factor(c("a", "b", "b", "c", "c", "c", "d", "d")))

I would like to summarise this data as one row and three columns (1X3) in tibble format.我想以 tibble 格式将这些数据总结为一行三列 (1X3)。 Where the first column show the counting of similar row values, the second column show the counting of different and the third column the total of values with final format as:其中第一列显示相似行值的计数,第二列显示不同行值的计数,第三列显示最终格式的值的总数:

final <- tibble(equal = 2, different = 6, total = 8)

thank you all谢谢你们

You could use你可以用

library(dplyr)
df %>% 
  summarise(equal = sum(as.numeric(var1) == as.numeric(var2)),
            different = sum(as.numeric(var1) != as.numeric(var2)),
            total = n())

This returns这返回

# A tibble: 1 x 3
  equal different total
  <int>     <int> <int>
1     2         6     8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM