我想找到每个家庭中人的总效用。SAMPN是家庭指数,PERNO是人指数。 每个人有2个实用程序,utility1和Utility2。我想为每个人添加该人的效用1和其他人的效用2。
SAMPN PERNO utility1 utility2
1 1 3 4
1 2 4 5
1 3 6 8
2 1 1 2
2 2 2 3
输出
SAMPN PERNO utility1 utility2 HH-utility
1 1 3 4 3+5+8=16
1 2 4 5 4+4+8=16
1 3 6 8 6+4+5=15
2 1 1 2 1+3=4
2 2 2 3 2+2=4
答案 0 :(得分:2)
按“ SAMPN”分组后,一个选项是获取“ {2}” sum
,从“ utility2”列中减去以获得没有元素的总和,然后向其中添加“ utility1”
library(dplyr)
df1 %>%
group_by(SAMPN) %>%
mutate(HHutility = sum(utility2) - utility2 + utility1)
# A tibble: 5 x 5
# Groups: SAMPN [2]
# SAMPN PERNO utility1 utility2 HHutility
# <int> <int> <int> <int> <int>
#1 1 1 3 4 16
#2 1 2 4 5 16
#3 1 3 6 8 15
#4 2 1 1 2 4
#5 2 2 2 3 4
或与base R
transform(df1, HHutility = utility1 + ave(utility2, SAMPN, FUN = sum) - utility2)
df1 <- structure(list(SAMPN = c(1L, 1L, 1L, 2L, 2L), PERNO = c(1L, 2L,
3L, 1L, 2L), utility1 = c(3L, 4L, 6L, 1L, 2L), utility2 = c(4L,
5L, 8L, 2L, 3L)), class = "data.frame", row.names = c(NA, -5L
))