Bomber Gay
Bomber Gay

Reputation: 39

Multiply columns in different dataframes

I am writing a code for analysis a set of dplyr data.

here is how my table_1 looks:

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

And my table_2 looks like this:

 1 D E F
 2 2 9 3 

I would love to based on table 1 column"A", if A>6, then create a column "G" in table1, equals to "C*D+C*E"

Basically, it's like make table 2 as a factor...

Is there any way I can do it?

I can apply a filter to Column "A" and multiply Column"C" with a set number instead of a factor from table_2

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

Upvotes: 1

Views: 166

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389325

You could try

#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

Using dplyr, we can do

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

Upvotes: 1

Related Questions