0

When I multiply a vector by a matrix I do:

mat <- matrix(c(c(2,3),c(4,5)),2)
vec <- c(1,-1) 
vec * mat

I get

     [,1] [,2]
[1,]    2    4
[2,]   -3   -5

But when I try to do something similar with tibbles, like

library(dplyr)
a <- tibble(x = c(1,-1))
b <- tibble(y = c(2,3), z = c(4,5))
c <- a*b

I get the error,

Error in Ops.data.frame(a, b) : 
  ‘*’ only defined for equally-sized data frames

In the same line of thought, how can I use transmute to multiply variable x by y and x by z in tibble d?

d <- tibble(x = c(1,-1), y=c(2,3), z= c(4,5))
Cettt
  • 11,460
  • 7
  • 35
  • 58
sbac
  • 1,897
  • 1
  • 18
  • 31

1 Answers1

1

You can use

d %>% mutate_at(vars(c(y, z)), ~.x*x)

or if you have more than two columns

d %>% mutate_at(vars(-x), ~.x*x)

Note that if you are working with an older version of the dplyr package you have to use a slightly different syntax which looks like this:

d %>% mutate_at(vars(-x), funs(. * x))
d %>% mutate_at(vars(c(y, z)), funs(. * x))
Cettt
  • 11,460
  • 7
  • 35
  • 58