【问题标题】:How to manipulate large arrays R如何操作大型数组 R
【发布时间】:2021-08-02 03:03:35
【问题描述】:

我有一个尺寸为data[1:10,1:50,1:1000] 的大型数组。我想用维度为new_data[1,1:50,1:1000] 的新数据替换所有矩阵的第 5 行。

到目前为止,我已经尝试将数组分开并重新组合在一起:

data1<-data[1:4,1:50,1:1000]
data2<-data[6:10,1:50,1:1000]

combined_data<-rbind(data1,new_data,data2) 

但是rbind 在这里似乎不合适,它返回一个大矩阵而不是带有dimensions[1:10,1:50,1:1000] 的大数组

这里有一个简单的例子:

vec1<-1:4
vec2<-c(1,2,2,4,1,2,2,4)
data_array<-array(c(vec1,vec2),dim=c(4,3,10))
data_array[,,1] # visualizing one of the 10 matrix - say they error is in row 3 where we would expect all 3s  


new_data<-array(c(3,3,3),dim=c(1,3,10))
new_data[,,1] # correct data that we want to swap into row 3 of all the matrices 

array2<-data_array[1:2,,] #correct data from original array 
array3<-array(data_array[4,,],dim=c(1,3,10)) #correct data from original array

combined_data <- rbind(array2,new_data,array3) # attempting to combine and new_data into the correct row 

但是,这会导致数据的维度为 [1:3,1:60],我的目标是与原始 data_array ([1:4,1:3,1:10]) 的维度完全相同但是在每个矩阵的第 3 行交换了 new_data

【问题讨论】:

标签: r data-manipulation rbind


【解决方案1】:

尝试使用“abind”包中的 abind。

library(abind)
array4 <- abind(array2,new_data,along=1) 
final_data <- abind(array4,array3,along=1)

参考如下:

http://math.furman.edu/~dcs/courses/math47/R/library/abind/html/abind.html

【讨论】:

  • 如果有人想知道我使用的最终解决方案是:array4
  • 我投了反对票,因为这不是答案。建议某人可以从中找出答案的文档页面是评论。具有讽刺意味的是,@AdSad 的上述评论是一个答案。如果您编辑了那段代码以显示 abind 的工作原理,我很乐意删除不赞成票,实际上给赞成票。
  • 了解,并采取相应措施@thelatemail
【解决方案2】:

由于数组实际上只是一个带维度的向量,因此您可以从第 3 个值(您要替换的行)开始,每隔 4 个值(每个层中的行数)替换一次,使用 new_data

data_array[seq(3, by=dim(data_array)[1], to=length(data_array))] <- new_data
data_array

#, , 1
#
#     [,1] [,2] [,3]
#[1,]    1    1    1
#[2,]    2    2    2
#[3,]    3    3    3
#[4,]    4    4    4
#
#, , 2
#
#     [,1] [,2] [,3]
#[1,]    1    1    1
#[2,]    2    2    2
#[3,]    3    3    3
#[4,]    4    4    4
#...

【讨论】:

    猜你喜欢
    • 2011-01-08
    • 2013-03-04
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 2014-12-19
    • 2010-11-18
    • 2010-09-16
    相关资源
    最近更新 更多