Select a matrix in a tibble with correct dimensions

Viewed 90

I have a tibble like this

dataf <- as_tibble( matrix(rnorm(12,0,1),nrow=4,ncol=3))

Its dimension is 4-by-3

I created a new column, which itself is a matrix:

dataf <- dataf %>% mutate(A = matrix(rnorm(8,0,1),nrow=4,ncol=2))

Though A is a 4-by-2 matrix, but the dimension of dataf is 4-by-4.

I hope

dataf %>% select(A)

returns a 4-by-2 tibble, so that I can set names for each column. However, this command still returns a 4-by-1 tibble.

So my question is how this select function can return a 4-by-2 tibble? Thanks!

2 Answers

wrap the matrix in I()

    dataf <- as_tibble( matrix(rnorm(12,0,1),nrow=4,ncol=3))
    dataf <- dataf %>% mutate(A = I(matrix(rnorm(8,0,1),nrow=4,ncol=2)))
    dataf %>% select(A) %>% as.matrix

If it's acceptable, you have to call as.matrix on it to get the actual matrix back

We can use pull, which is like the $ sign in base R.

library(dplyr)

A <- dataf %>% pull(A)

class(A)
# [1] "matrix" "array"

dim(A)
# [1] 4 2
Related