1

我正在编写用于分析一组 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))
4

1 回答 1

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))
于 2019-07-25T04:32:29.680 回答