如何进行总结,然后将结果乘以组? 数据

问题描述

这是我的数据框。 Country1 代表居住在德国的人,Country 2 代表他们在搬到 Country1 之前居住的国家 5 年。

国家 1 Country2 重量 关注
德国 德国 4 1
德国 德国 119 2
法国 德国 3 3
法国 德国 2 4
意大利 法国 1 5

基本上我想要的是总结每个组合的列权重和乘以观察(由列 obs 表示。例如,在第一行我有德国到德国的组合,所以我想要什么是将 Weight (119+4=123) 列的权重相加,然后将这个总和的结果 (123* 1=123) 乘以 Obs (1) 列(在第一行中)的相应观察值。对于第二行将与德国的权重汇总相同 (119+4=123),并且在这种情况下,该结果必须乘以该行的观察结果 (123*2=246)。在第三行中行权重之和为 (3+2=5),然后将此结果乘以该行的观测值 (5* 3=15),依此类推。

我想要的输出由 x 列表示,就像这样。

国家 1 Country2 重量 关注 x
德国 德国 4 1 123
德国 德国 119 2 246
法国 德国 3 3 15
法国 德国 2 4 20
意大利 法国 1 5 5

我尝试应用的公式也是这个。

enter image description here

解决方法

你也可以这样解决:

df1$x <- tapply(df1$Weight,df1$Country1,sum)[df1$Country1] * df1$obs

  Country1 Country2 Weight obs   x
1  Germany  Germany      4   1 123
2  Germany  Germany    119   2 246
3   France  Germany      3   3  15
4   France  Germany      2   4  20
5    Italy   France      1   5   5
,

试试这个:

library(dplyr)
#Code
new <- df %>% group_by(Country1) %>%
  mutate(x=sum(Weight)*obs)

输出:

# A tibble: 5 x 5
# Groups:   Country1 [3]
  Country1 Country2 Weight   obs     x
  <chr>    <chr>     <int> <int> <int>
1 Germany  Germany       4     1   123
2 Germany  Germany     119     2   246
3 France   Germany       3     3    15
4 France   Germany       2     4    20
5 Italy    France        1     5     5

使用的一些数据:

#Data
df <- structure(list(Country1 = c("Germany","Germany","France","Italy"),Country2 = c("Germany","France"),Weight = c(4L,119L,3L,2L,1L),obs = 1:5),class = "data.frame",row.names = c(NA,-5L))
,

我们可以使用 data.table 方法

library(data.table)
setDT(df1)[,x := sum(Weight) *obs,by = Country1][]

-输出

#   Country1 Country2 Weight obs   x
#1:  Germany  Germany      4   1 123
#2:  Germany  Germany    119   2 246
#3:   France  Germany      3   3  15
#4:   France  Germany      2   4  20
#5:    Italy   France      1   5   5

或者将 base Rave 一起使用

df1$x <- with(df1,ave(Weight,Country1,FUN = sum) * obs)

数据

df1 <- structure(list(Country1 = c("Germany",-5L))