Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert dataframe to 3D array

Tags:

arrays

r

I need to convert a dataframe to an array of 3 dimensions. All columns in the dataframe are numeric. What is an elegant and/or efficient way to accomplish this?

Example:

x <- 1:3
y <- 1:3

g <- t(vapply(x, function(x){ 
      vapply(y, function(y){ 
          as.numeric(paste(x,y,sep="."))}, numeric(1))}, numeric(3)))

gdf <- data.frame( cbind(rep(1:3,each=3), rbind(g, g*2, g*3)) )

I want to convert "gdf" to an array where gdf$x1 defines the third dimension. The result would look like this:

ga <- array( c(g, g*2, g*3), dim=c(3,3,3) )

Thanks!

like image 407
npell Avatar asked Apr 30 '26 22:04

npell


1 Answers

This works with your example, I hope it will be general enough for you:

gb <- aperm(array(unlist(gdf[, -1]), c(3, 3, 3)), c(1, 3, 2))

identical(ga, gb)
# [1] TRUE
like image 83
flodel Avatar answered May 03 '26 10:05

flodel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!