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
谢谢
推荐答案
以下是许多解决方案:
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屋!
查看全文