Tidyr 如何传播到发生次数 [英] Tidyr how to spread into count of occurrence
本文介绍了Tidyr 如何传播到发生次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一个这样的数据框
other=data.frame(name=c("a","b","a","c","d"),result=c("Y","N","Y","Y","N"))
如何在 tidyr 或其他函数中使用扩展函数来获取结果 Y 或 N 的计数作为这样的列标题
How can I use spread function in tidyr or other function to get the count of result Y or N as column header like this
name Y N
a 2 0
b 0 1
谢谢
推荐答案
以下是解决方案的几种方法:
These are a few ways of many to go about it:
1) 使用库 dplyr
,您可以简单地将事物分组并计算为所需的格式:
1) With library dplyr
, you can simply group things and count into the format needed:
library(dplyr)
other %>% group_by(name) %>% summarise(N = sum(result == 'N'), Y = sum(result == 'Y'))
Source: local data frame [4 x 3]
name N Y
<fctr> <int> <int>
1 a 0 2
2 b 1 0
3 c 0 1
4 d 1 0
2) 您可以使用 table
和 tidyr
的组合传播如下:
2) You can use a combination of table
and tidyr
spread as follows:
library(tidyr)
spread(as.data.frame(table(other)), result, Freq)
name N Y
1 a 0 2
2 b 1 0
3 c 0 1
4 d 1 0
3) 您可以使用 dplyr
和 tidyr
的组合来执行以下操作:
3) You can use a combination of dplyr
and tidyr
to do as follows:
library(dplyr)
library(tidyr)
spread(count(other, name, result), result, n, fill = 0)
Source: local data frame [4 x 3]
Groups: name [4]
name N Y
<fctr> <dbl> <dbl>
1 a 0 2
2 b 1 0
3 c 0 1
4 d 1 0
这篇关于Tidyr 如何传播到发生次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文