Question

I have two data frames

data frame 1

A B C

1 1 0
0 0 0
1 1 0

data frame 2

  1 2   

  0 4  
100 0  
100 4  

I need to multiply and combine the columns to obtain

A1  A2  B1  B2  C1  C2

0   4   0   4   0   0
0   0   0   0   0   0
100 4   100 4   0   0
Était-ce utile?

La solution

Here's one approach:

do.call(cbind, lapply(df1, "*", as.matrix(df2)))

       1 2   1 2 1 2
[1,]   0 4   0 4 0 0
[2,]   0 0   0 0 0 0
[3,] 100 4 100 4 0 0

This returns a matrix. You can use as.data.frame to turn it into a data frame if it's necessary.


This is based on the following data:

df1 <- data.frame(A = c(1,0,1), B = c(1,0,1), C = 0)

df2 <- data.frame("1" = c(0,100,100), "2" = c(4,0,4),
                  check.names = FALSE)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top