我的数据框如下:
name<-c("ab","ab","ab","ac","ac","ac","d","d","d")
value<-c(4,5,6,7,3,4,8,9,8)
week<-c(31,31,32,31,31,35,32,33,35)
c<-data.frame(name,value,week)
我想要的是创建一个新列,这些列的名称之和同名,然后属于同一周。结果应该是:
name value week sum
1 ab 4 31 9
2 ab 5 31 9
3 ab 6 32 6
4 ac 7 31 10
5 ac 3 31 10
6 ac 4 35 4
7 d 8 32 8
8 d 9 33 9
9 d 8 35 8
答案 0 :(得分:1)
使用循环的一种方式
c$sum <- rep(NA,nrow(c))
for(i in 1:nrow(c)) {
c$sum[i] <- sum(subset(c, name==c[i,'name'] & week==c[i,'week'])[,'value'])
}
结果:
name value week sum
1 ab 4 31 9
2 ab 5 31 9
3 ab 6 32 6
4 ac 7 31 10
5 ac 3 31 10
6 ac 4 35 4
7 d 8 32 8
8 d 9 33 9
9 d 8 35 8