How would I execute this algebra operation? What would this be called?

I asked a similar question before, but now it's slightly different, and stuck on trying to figure it out. Here is a visual:

Essentially, x can have any number of rows and columns, while y can only have any number of columns. When the two dataframes have the same column names, I would like them to be multiplied. If the columns in x do not exist in y, then they can be left alone (or multiplied by 1).

x = data.frame(var1 = c(1, 2, 3),
               var2 = c(3, 4, 5),
               var3 = c(5, 6, 7),
               var4 = c(7, 8, 9))

y = data.frame(var1 = 2,
               var2 = 5)

How is this different from before ? can you emphasise the difference ?
your screenshot for y shows var3 as 5 but your code has var 2 as 5. I went with the screenshot.
I provide the same solution you were provided before, but put into a function, so hopefully you can reuse it with greater ease.

x = data.frame(var1 = c(1, 2, 3),
               var2 = c(3, 4, 5),
               var3 = c(5, 6, 7),
               var4 = c(7, 8, 9))


y = data.frame(var1 = 2,
               var3 = 5)

mycalc <- function(x,y){
require(dplyr)
xm <- as.matrix(x)
#padd y with 1's
toadd <- setdiff(names(x),names(y))
y[toadd] <- 1
y <- select(y,names(x))
ym <- as.matrix(y)

xm %*% t(ym)
}

mycalc(x,y)

Ah the difference is that in the previous thread, the results are in one column. This one is into multiple columns.

If I'm understanding your code correctly, it seems that this will result in one column. I will have to check it later today.

yes, it does one column...
Here is the full frame

x = data.frame(var1 = c(1, 2, 3),
               var2 = c(3, 4, 5),
               var3 = c(5, 6, 7),
               var4 = c(7, 8, 9))


y = data.frame(var1 = 2,
               var3 = 5)

mycalc <- function(x,y){
require(dplyr)
require(purrr)
#padd y with 1's
(toadd <- setdiff(names(x),names(y)))
y[toadd] <- 1
y <- select(y,names(x))

map2_dfc(x,y,~.x*.y)
}

mycalc(x,y)
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.