有一个包含嵌套信息的数据框.让我们说出每所学校的学生人数,A班学生人数和B班学生人数.因此,学生= n.pupilsA + n.pupilsB + other_pupils
a <- data.frame(
city = c(rep('New York',3), rep('Washington',3)),
n = c(5, 2, 1, 5, 2, 1),
name = c(
'pupils',
'classA',
'classB',
'pupils',
'classA',
'classB'
)
)
Run Code Online (Sandbox Code Playgroud)
输出:
city n name
1 New York 5 pupils
2 New York 2 classA
3 New York 1 classB
4 Washington 5 pupils
5 Washington 2 classA
6 Washington 1 classB
Run Code Online (Sandbox Code Playgroud)
是否有一种聪明的方法(使用dplyr,大概是)进行小组操作,这将增加每个组"其他",这将是"学生"和"学生 - A级"+"学生 - B级"之间的差异.所以结果会是这样的:
city type npupils
1 New York classA 2
2 New York classB 1
3 New York pupils 5
4 New York other 2
5 Washington classA 2
6 Washington classB 1
7 Washington pupils 5
8 Washington other 2
Run Code Online (Sandbox Code Playgroud)
我认为可行的唯一方法是传播它,计算列之间的差异,然后使用tidyr以下方法收集它:
a %>%
spread(name, n) %>%
mutate(other = pupils - classA - classB) %>%
gather(type, npupils, c('classA', 'classB', 'pupils', 'other')) %>%
arrange(city)
Run Code Online (Sandbox Code Playgroud)
哪个有效,但我想知道是否有更好的方法?
我们可以创建一个汇总的数据框并将其绑定到原始数据框.对于每个,city我们n通过减去组中剩余值的nwhere 值来计算,name == 'pupils'并将name列创建为"Other",并使用将这些行添加到原始数据框中bind_rows.
library(dplyr)
bind_rows(a, a %>%
group_by(city)%>%
summarise(n = n[name == 'pupils'] - sum(n[name != 'pupils']),
name = "Other")) %>%
arrange(city)
# city n name
#1 New York 5 pupils
#2 New York 2 classA
#3 New York 1 classB
#4 New York 2 Other
#5 Washington 5 pupils
#6 Washington 2 classA
#7 Washington 1 classB
#8 Washington 2 Other
Run Code Online (Sandbox Code Playgroud)
注意 - 在这里我假设你每个city人只有一个"学生"条目,否则我们可以which.max用来获得第一个条目.