How to give names to the inner columns in a matrix column?

How do I give names to the columns in a matrix column so that unnest_wider doesn't output a message?

df <- data.frame(x = 1:2)
df$y <- matrix(1:6, ncol = 3)

df <- df %>% 
  rowwise() %>% 
  summarise(y = list(y))

df %>%
  mutate(y = asplit(y, 1)) %>% 
  unnest_wider(c(y))

Similar question to: How to handle lack of names with unnest_wider()

Same as for any matrix:

df <- data.frame(x = 1:2)
df$y <- matrix(1:6, ncol = 3)
colnames(df$y) <- letters[1:3]

df %>%
  mutate(y = asplit(y, 1)) %>% 
  unnest_wider(y)

1 Like

Could you post a reprex (minimal reproducible example)?

The code I have showed you works, so there must be something special about you are doing.

Also the whole approach is quite strange (adding a matrix to a df to turn it into a list and then to columns) and if provided with a little more context, perhaps me or someone else could indeed propose a very different way to tackle your issue.

For example, why don't you first convert the matrix into a data.frame to begin with and then column-bind the 2 data.frames?

1 Like

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

Do you know any other ways of thinking of thinking about this question? In my real data when I try this approach I get the error

Error in `colnames<-`(`*tmp*`, value = c("agent_rating_comb1", "agent_rating_comb2",  : 
  attempt to set 'colnames' on an object with less than two dimensions

edit: i think this is because my matrix's are nested in a list column, so I've edited the question. My bad.