Eli
Eli

Reputation: 290

Split matrix into columns and store in variables

I have a matrix with n rows and d columns. For example,

n = 100; d = 3
mat = matrix(rnorm(n * d) ncol = d)

I need to take the columns of the matrix and assign them to variables x1, x2,..., xd. The number of columns will not be fixed.

I've tried splitting the matrix and assigning it with an mapply statement but no assignment happens:

nam = paste0("x", 1:d)
column_vectors = split(x, rep(1:ncol(x), each = nrow(x)))
mapply(FUN = assign, nam, column_vectors)

I could do this by brute force but there must be a simpler, cleaner way.

nam = paste0("x", 1:d)
column_vectors = split(x, rep(1:ncol(x), each = nrow(x)))
for(i in seq_along(column_vectors)){

  assign(nam[i], column_vectors[[i]]) 
}

Upvotes: 0

Views: 96

Answers (1)

Jilber Urbina
Jilber Urbina

Reputation: 61154

You can try this approach:

matList <- unlist(apply(mat, 2, list),  recursive = FALSE)
names(matList) <- paste0("x", 1:d)
list2env(matList, envir = globalenv())

Upvotes: 1

Related Questions