将不同数据框中的列相乘

时间:2019-07-25 03:10:13

标签: r dplyr multidplyr

我正在编写用于分析一组dplyr数据的代码。

这是我的table_1的外观:

 1 A B C
 2 5 2 3
 3 9 4 1
 4 6 3 8
 5 3 7 3

我的table_2看起来像这样:

 1 D E F
 2 2 9 3 

我希望基于表1的列“ A”,如果A> 6,则在表1中创建列“ G”,等于“ C*D+C*E

基本上,就像把表2作为一个因素...

有什么办法可以做到吗?

我可以对“ A”列应用过滤器,然后将“ C”列与设置的数字相乘,而不是与table_2中的因子相乘

 table_1_New <- mutate(Table_1,G=if_else(A<6,C*2+C*9))

1 个答案:

答案 0 :(得分:1)

您可以尝试

#Initialize G column with 0
df1$G <- 0
#Get index where A value is greater than 6
inds <- df1$A > 6
#Multiply those values with D and E from df2
df1$G[inds] <- df1$C[inds] * df2$D + df1$C[inds] * df2$E
df1

#  A B C  G
#2 5 2 3  0
#3 9 4 1 11
#4 6 3 8  0
#5 3 7 3  0

使用dplyr,我们可以做到

df1 %>% mutate(G = ifelse(A > 6, C*df2$D + C*df2$E, 0))