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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With