[英]R: How to sum values from rows only if the key value is the same and also if the key duplicated in consecutive rows?
[英]Sum of consecutive same rows in R
我有像下面给出的数据。
V1 V2 V3
6.9 6.2 4590
6.9 6.2 1340
7.1 6.2 3000
7.2 6.3 3490
我想要得到的输出是
V1 V2 V3
6.9 6.2 avg(4590,1340)
7.1 6.2 3000
7.2 6.3 3490
目的是在V1和V2中的连续值相同的情况下查找V3的平均值。
提前致谢..
我们可以使用aggregate
aggregate(V3~., df1, mean)
# V1 V2 V3
#1 6.9 6.2 2965
#2 7.1 6.2 3000
#3 7.2 6.3 3490
要么
library(data.table)
setDT(df1)[, list(V3= mean(V3)) ,.(V1, V2)]
要么
library(dplyr)
df1 %>%
group_by(V1, V2) %>%
summarise(V3= mean(V3))
或与sqldf
library(sqldf)
sqldf('select V1, V2,
avg(V3) as V3
from df1
group by V1, V2')
df1 <- structure(list(V1 = c(6.9, 6.9, 7.1, 7.2),
V2 = c(6.2, 6.2, 6.2,
6.3), V3 = c(4590L, 1340L, 3000L, 3490L)),
.Names = c("V1", "V2",
"V3"), class = "data.frame", row.names = c(NA, -4L))
这是一个plyr
解决方案:
require(plyr)
> ddply(df, .(V1, V2), summarise, V2=mean(V2), V3=mean(V3))
V1 V2 V3
1 6.9 6.2 2965
2 7.1 6.2 3000
3 7.2 6.3 3490
请注意,用SQL术语来说,您希望按列V1
和V2
的组合进行分组,该列在第二个参数中表示为.(V1, V2)
。
数据:
df <- data.frame(V1=c(6.9, 6.9, 7.1, 7.2),
V2=c(6.2, 6.2, 6.2, 6.3),
V3=c(4590, 1340, 3000, 3490))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.