R中的2D矩阵到3D堆叠数组 [英] 2d matrix to 3d stacked array in r

查看:91
本文介绍了R中的2D矩阵到3D堆叠数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在昏暗的120000行乘5列的R中有一个数据帧data.

I have a dataframe data in R of dim 120000 rows by 5 columns.

每300线是在不同时间间隔(即400帧)测量的一帧

Each 300 lines is a frame measured at different time intervals (ie 400 frames)

操作

我尝试使用array(data, c(300, 5, 400))

期望

通过每300行分割data将此数据帧制成3d数组,并将这400个矩阵彼此堆叠.

Make this dataframe into a 3d array by splitting data every 300 lines and stack these 400 matrices behind each other.

实际

沿data的第一列向下读取值,并将其放入数组的第一部分.

Reads the values down along the first column of data and puts these into the first part of the array.

推荐答案

另一个选择是:

 m1 <- matrix(1:(300*400*5), nrow=300*400, ncol=5)
 lst <- lapply(split(seq_len(nrow(m1)),(seq_len(nrow(m1))-1) %/%300 +1),
                         function(i) m1[i,])

 arr1 <- array(0, dim=c(300,5,400))
 for(i in 1:400){
 arr1[,,i] <- lst[[i]]
 }

m1[297:300,]
#     [,1]   [,2]   [,3]   [,4]   [,5]
#[1,]  297 120297 240297 360297 480297
#[2,]  298 120298 240298 360298 480298
#[3,]  299 120299 240299 360299 480299
#[4,]  300 120300 240300 360300 480300

 tail(arr1[,,1],4)
 #      [,1]   [,2]   [,3]   [,4]   [,5]
 #[297,]  297 120297 240297 360297 480297
 #[298,]  298 120298 240298 360298 480298
 #[299,]  299 120299 240299 360299 480299
 #[300,]  300 120300 240300 360300 480300

或如@Ananda Mahto所建议

Or as suggested by @Ananda Mahto

library(abind)
arr2 <-  abind(lapply(split(seq_len(nrow(m1)), 
           (seq_len(nrow(m1))-1) %/% 300 + 1), function(x) m1[x, ]), along = 3)

这篇关于R中的2D矩阵到3D堆叠数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆