Search code examples
rdplyrtidyselect

Create a matrix from all variables in each row


I have a dataframe that stores a set of vectorized matrices. That is, in each row, I have the NxM variables that correspond to the elements in the matrix.

Given this dataframe, I would like to apply a function to the matrix stored in each row, and then store the result in a new variable.

A naive way to do it is to specify the names of the NxM variables. For instance, if the function I want to apply is just the sum of the elements (in the real case it computes the likelihood of that matrix):

library(dplyr)
cars %>% rowwise() %>% mutate(matrix=sum(matrix(c(speed,dist), nrow=1, ncol=2)))

But since the dimension of my matrices may change from one experiment to another, and since this dimensions is often to big to enumerate all the variables, I would like a generic solution.

I try with

library(dplyr)
cars %>% rowwise() %>% mutate(matrix=sum(matrix(everything(), nrow=1, ncol=2)))

(in this example, ncol and nrow should be adapted to fit the current number of variables, but that I can do it by hand.)

But this raises the error:

Error in mutate_impl(.data, dots) : Evaluation error: No tidyselect variables were registered.

Is there a simple way to do it?


Solution

  • The purrrlyr-package may be useful

    get_matrix_sum <- function(x) {x %>% as.matrix() %>% sum()}
    cars %>% purrrlyr::by_row(..f = get_matrix_sum, .collate = "rows", .to = "matrix")