rdplyrsumproductcross-product

Is there a way to apply a crossproduct to a new column in R using mutate?


I have a dataframe of all 1's and 0's, and a vector related to each column in the data frame, and I want to create a new column in the data frame that is the sumproduct of each row in the data frame and the vector. Consider this example:

    dataframe <- data.frame(a = c(1, 1, 1), b = c(0, 1, 0), c = c(1, 1, 0))
    > dataframe
      a b c
    1 1 0 1
    2 1 1 1
    3 1 0 0
    > nums <- c(100, 200, 300)
    > nums
    [1] 100 200 300

I then would want a column d to equal (400, 600, 100). I know I can do this by writing a loop, but am trying to use mutate and crossprod and am getting the error "requires numeric/complex matrix/vector arguments"

Thanks!


Solution

  • You could do:

    dataframe %>% mutate(d = as.matrix(.) %*% nums)
    
    #>   a b c   d
    #> 1 1 0 1 400
    #> 2 1 1 1 600
    #> 3 1 0 0 100
    

    or

    dataframe %>% mutate(d = crossprod(t(as.matrix(.)), nums))
    
    #>   a b c   d
    #> 1 1 0 1 400
    #> 2 1 1 1 600
    #> 3 1 0 0 100