Syd Amerikaner
Syd Amerikaner

Reputation: 105

Gather a tibble with matrix columns

My tibble looks like this:

df = tibble(x = 1:3, col1 = matrix(rnorm(6), ncol = 2), 
                col2 = matrix(rnorm(6), ncol = 2))

it has three columns of which two contain a matrix with 2 columns each (in my case there are many more columns, this example is just to illustrate the problem). I transform this data to long format by using gather

gather(df, key, val, -x)

but this gives me not the desired result. It stacks only the first column of column 1 and column 2 and dismisses the rest. What I want is that val contains the row vectors of column 1 and column 2, i.e. val is a matrix valued column (containing 1x2 matrices). The tidyverse seems, however, not be able to deal with matrix-valued columns appropriately. Is there a way to achieve my desired result? (Ideally using the routines from tidyverse)

Upvotes: 1

Views: 808

Answers (1)

akrun
akrun

Reputation: 887981

Some of the columns are matrix. It needs to be converted to proper data.frame columns and then would work

library(dplyr)
library(tidyr) 
do.call(data.frame, df) %>%
       pivot_longer(cols = -x)

Or use gather

do.call(data.frame, df) %>%
       gather(key, val, -x)

Or another option is to convert the matrix to vector with c and then use unnest

df %>%
     mutate_at(-1,   ~ list(c(.))) %>%
     unnest(c(col1, col2))

if the 'col1', 'col2', values would be in a single column

df %>%
    mutate_at(-1,   ~ list(c(.))) %>%
    pivot_longer(cols = -x) %>% 
    unnest(c(value))

Upvotes: 3

Related Questions