我希望按列(所有者)对数据框进行分组,并输出一个新数据框,该数据框包含每次观察时每种因子类型的计数。真实的数据框架相当大,有10个不同的因素。
以下是一些示例输入:
library(dplyr)
df = tbl_df(data.frame(owner=c(0,0,1,1), obs1=c("quiet", "loud", "quiet", "loud"), obs2=c("loud", "loud", "quiet", "quiet")))
owner obs1 obs2
1 0 quiet loud
2 0 loud loud
3 1 quiet quiet
4 1 loud quiet
我一直在寻找看起来像这样的输出:
out = data.frame(owner=c("0", "0", "1", "1"), observation=c("obs1", "obs2", "obs1", "obs2"), quiet=c(1, 0, 1, 2), loud=c(1, 2, 1, 0))
owner observation quiet loud
1 0 obs1 1 1
2 0 obs2 0 2
3 1 obs1 1 1
4 1 obs2 2 0
融化让我在那里:
melted = tbl_df(melt(df, id=c("owner")))
owner variable value
1 0 obs1 quiet
2 0 obs1 loud
3 1 obs1 quiet
4 1 obs1 loud
5 0 obs2 loud
6 0 obs2 loud
7 1 obs2 quiet
8 1 obs2 quiet
但是最后一步是什么?如果'value'是一个数字,我就去:
melted %>% group_by(owner, variable) %>% summarise(counts=sum(value))
非常感谢!
答案 0 :(得分:25)
您可以将tidyr
与dplyr
library(dplyr)
library(tidyr)
df %>%
gather(observation, Val, obs1:obs2) %>%
group_by(owner,observation, Val) %>%
summarise(n= n()) %>%
ungroup() %>%
spread(Val, n, fill=0)
给出输出
# owner observation loud quiet
#1 0 obs1 1 1
#2 0 obs2 2 0
#3 1 obs1 1 1
#4 1 obs2 0 2
答案 1 :(得分:24)
2017年答案是
library(dplyr)
library(tidyr)
gather(df, key, value, -owner) %>%
group_by(owner, key, value) %>%
tally %>%
spread(value, n, fill = 0)
提供输出
Source: local data frame [4 x 4]
Groups: owner, key [4]
owner key loud quiet
* <dbl> <chr> <dbl> <dbl>
1 0 obs1 1 1
2 0 obs2 2 0
3 1 obs1 1 1
4 1 obs2 0 2
答案 2 :(得分:3)
如果您想放弃dplyr
,可以拆分成列表。
df <- split(df, list(df[[obs1]], df[[obs2]])
如果您想要count
,则只需创建一个sapply
或lapply
来调用列表并获取每个列表的计数。或者字面上你想要的任何其他功能。