使用来自不同数据帧的列对多个组执行计算

问题描述 投票:0回答:2

我想对多个组执行简单计算,其中来自单独数据帧的列基于唯一标识符进行相乘。这是第一个数据框:

year1 <- c(rep(2016,3),rep(2017,3),rep(2018,3))
group <- rep(letters[1:3],3)
prop <- c(0.3,0.6,0.1,0.4,0.3,0.3,0.2,0.5,0.3)
df1 <- as.data.frame(cbind(year1,group,prop))
df1$prop <- as.numeric(as.character(df1$prop))

这是第二个:

year2 <- c(2016,2017,2018)
value <- c(325,483,742)
df2 <- as.data.frame(cbind(year2,value))

我现在想在第一个数据框中添加一个列,其中year1 group中的每个df1propvalue中相应的year2df2相乘。

理论上,使用group_bymutate的解决方案可以解决问题,但我不知道如何使用这些命令为两个数据帧索引year。任何建议将不胜感激。谢谢!

r loops dplyr data.table grouping
2个回答
3
投票

您可以通过两个表之间的连接来实现此目的。这可以使用merge函数在base R中完成,或者使用几个join函数之一在dplyr中完成。我在这个例子中使用了left_join。

您的df1数据框示例将年份设置为一个因子,因此必须首先将其转换为数字。您的真实数据可能没有这个问题。以下示例中的左连接用于确保df1中的所有行都出现在连接结果中。

df1$year1 = as.numeric(as.character(df1$year1))
df3 = 
  left_join(df1, df2, by = c("year1" = "year2")) %>%
  mutate(result = prop * value)

>df3
  year1 group prop value result
1  2016     a  0.3   325   97.5
2  2016     b  0.6   325  195.0
3  2016     c  0.1   325   32.5
4  2017     a  0.4   483  193.2
5  2017     b  0.3   483  144.9
6  2017     c  0.3   483  144.9
7  2018     a  0.2   742  148.4
8  2018     b  0.5   742  371.0
9  2018     c  0.3   742  222.6

0
投票

其他方式:

## using data.table
setDT(df1)
setDT(df2)

# set column types of key columns to be same
df1[, year1 := as.numeric()]

# merge files and get result
df1 <- merge(df1, df2, by.x = 'year1', by.y = 'year2')
df1[,result := prop*value, .(year1, group)]

   year1 group prop value result
1:  2016     a  0.3   325   97.5
2:  2016     b  0.6   325  195.0
3:  2016     c  0.1   325   32.5
4:  2017     a  0.4   483  193.2
5:  2017     b  0.3   483  144.9
6:  2017     c  0.3   483  144.9
7:  2018     a  0.2   742  148.4
8:  2018     b  0.5   742  371.0
9:  2018     c  0.3   742  222.6
© www.soinside.com 2019 - 2024. All rights reserved.