How to manipulate large arrays R

Viewed 218

I have a large array with dimensions data[1:10,1:50,1:1000]. I would like to swap out the 5th row of all the matrices with new data with the dimensions new_data[1,1:50,1:1000].

So far I have tried to pull the array apart and put it back together:

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

combined_data<-rbind(data1,new_data,data2) 

However rbind doesn't seem to be appropriate here and returns a large matrix rather than a large array with dimensions[1:10,1:50,1:1000]

On request here is a simple example:

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 

However this results in a data with the dimensions [1:3,1:60], where I am aiming for the exact same dimensions as the original data_array ([1:4,1:3,1:10]) but with the new_data swapped in at row 3 of each matrix

2 Answers

Since an array is really just a vector with dimensions, you can replace every 4th value (the number of rows in each stratum), starting at the 3rd value (the row you want to replace), with the 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
#...
Related