具有此数据框:
lt vl
1 a 1.0
2 2.0
3 0.5
4 6.0
5 7.0
6 a 6.0
7 8.0
8 7.0
9 9.0
10 d 7.0
11 NA
12 0.5
13 8.0
14 5.0
15 g 6.0
16 7.0
lt<-c("a","","","","","a","","","","d","","","","","g","")
vl<-c(1,2,0.5,6,7,6,8,7,9,7,NA,0.5,8,5,6,7)
我想对vl
的字符之间的lt
中的每个值求和。该过程必须是这样的:
a=1+2+0.5+6+7
a=6+8+7+9
d=7+0.5+8+5
g=6+7
最终获得:
lt vl
a 16.5
a 30
d 20.5
g 13
注意:a
与a
我正在努力解决这个问题,但是对我来说却很难。
答案 0 :(得分:2)
您可以使用tapply
进行此操作。分组因子是通过标准的cumsum
技巧建立的。
f <- cumsum(lt != "")
res <- tapply(vl, f, FUN = sum, na.rm = TRUE)
names(res) <- lt[lt != ""]
res
# a a d g
#16.5 30.0 20.5 13.0