您可以使用dplyr 做您想做的事。我们首先group_byPIN,然后使用mutate创建一个新列Total,这是分组Balance的总和:
library(dplyr)
res <- df %>% group_by(PIN) %>% mutate(Total=sum(Balance))
将您的数据用作数据框df:
df <- structure(list(PIN = c(221L, 221L, 221L, 554L, 554L, 643L, 643L
), Balance = c(5000L, 2000L, 1000L, 4000L, 4500L, 6000L, 4000L
)), .Names = c("PIN", "Balance"), class = "data.frame", row.names = c(NA,
-7L))
## PIN Balance
##1 221 5000
##2 221 2000
##3 221 1000
##4 554 4000
##5 554 4500
##6 643 6000
##7 643 4000
我们得到了预期的结果:
print(res)
##Source: local data frame [7 x 3]
##Groups: PIN [3]
##
## PIN Balance Total
## <int> <int> <int>
##1 221 5000 8000
##2 221 2000 8000
##3 221 1000 8000
##4 554 4000 8500
##5 554 4500 8500
##6 643 6000 10000
##7 643 4000 10000
或者我们可以使用data.table:
library(data.table)
setDT(df)[,Table:=sum(Balance),by=PIN][]
## PIN Balance Total
##1: 221 5000 8000
##2: 221 2000 8000
##3: 221 1000 8000
##4: 554 4000 8500
##5: 554 4500 8500
##6: 643 6000 10000
##7: 643 4000 10000