R 根据特定值汇总行数
这是我的数据帧R 根据特定值汇总行数,r,R,这是我的数据帧 Colour = c("red", "blue", "red", "blue", "yellow", "green", "red", "blue", "green", "red", "yellow", "blue") Volume = c(46,46,57,57,57,57,99,99,99,111,111,122) Cases = c(7,2,4,2,3,5,1,2,3,2,4,1) df = data.frame(Colour, Volum
Colour = c("red", "blue", "red", "blue", "yellow", "green", "red", "blue", "green", "red", "yellow", "blue")
Volume = c(46,46,57,57,57,57,99,99,99,111,111,122)
Cases = c(7,2,4,2,3,5,1,2,3,2,4,1)
df = data.frame(Colour, Volume, Cases)
我想总结一下,如果颜色是“红色”
或“蓝色”
,但音量是相同的情况。
未指定的颜色应保留。如果红色和蓝色不能相加
因为它们在音量上不同
所以也应该保留它们
reult应该是这样的:
Colour = c("red_or_blue","red_or_blue","yellow","green","red_or_blue","green","red","yellow","blue")
Volume = c(46,57,57,57,99,99,111,111,122)
Cases = c(9,6,3,5,3,3,2,4,1)
df_agg = data.frame(Colour, Volume, Cases)
我找到了一种方法,可以创建另一个列,为红色或蓝色的行分配一个“red\u or\u blue”
,其余的行分配一个x。然后我使用了聚合:
df$test = ifelse(df$Colour %in% c("red", "blue"),"red_or_blue","x")
df_agg = aggregate(df$Cases, list(df$Volume, df$test), sum)
它可以工作,但我觉得这有点麻烦。有没有更方便的方法可以跳过创建额外的列?将来我需要总结红色/蓝色和第57/99卷的案例。拥有额外的列似乎会让它变得有点棘手
而且,如果不是红色或蓝色,我也没有设法让原色被取代。我试过这样做,但不起作用:
df$test = ifelse(df$Colour %in% c("red", "blue"),"red_or_blue",df$Colour)
干杯,保罗这里有一个坚持R垒的方法(但可能不是最有效的方法……)
Volume
temp = split(df, df$Volume)
temp
对象上使用该函数:
temp = lapply(temp, red.and.blue)
aggregate()
执行需要执行的聚合。在aggregate()
参数中指定名称,以便保留原始列名
temp = lapply(temp, function(x) aggregate(list(Cases = x$Cases),
list(Colour = x$Colour,
Volume = x$Volume), sum))
data.frame()
中。如果要按原样存储,请不要忘记指定名称
do.call(rbind, temp)
# Colour Volume Cases
# 46 red-and-blue 46 9
# 57.1 green 57 5
# 57.2 red-and-blue 57 6
# 57.3 yellow 57 3
# 99.1 green 99 3
# 99.2 red-and-blue 99 3
# 111.1 red 111 2
# 111.2 yellow 111 4
# 122 blue 122 1
我认为如果您遵循@mrdwab的方法,您可以在每个“分割卷”上使用
sapply
df$当然,请适当地编辑“红色或蓝色
”而不是我在这里所做的“红色和蓝色
”。谢谢mrdwab。它运行良好,比我的方式更优雅。按照您的方式操作,我如何同时聚合体积,即如果颜色=红色或蓝色,则聚合;如果体积=46或57,则聚合。按照我的方式,我只需添加一个新列。用你的方法,我首先为第46卷或第57卷创建了一个新公式,然后我需要在步骤3ff中整合它。
do.call(rbind, temp)
# Colour Volume Cases
# 46 red-and-blue 46 9
# 57.1 green 57 5
# 57.2 red-and-blue 57 6
# 57.3 yellow 57 3
# 99.1 green 99 3
# 99.2 red-and-blue 99 3
# 111.1 red 111 2
# 111.2 yellow 111 4
# 122 blue 122 1
df$Cases <- sum(df[(df$Colour =='blue' | df$Colour == 'red'),][,3])
df$Colour[(df$Colour =='blue' | df$Colour == 'red')] <- 'readandblue'