简体   繁体   中英

R fixed length array of empty arrays

I know this has been asked a bunch previously but I was having trouble making sense of what I found. I am looking to create a fixed length array of array of doubles in R, what would be the correct declaration for this? I think want to be able to push elements into these arrays, something like array[1][]=0.1 , array[2][]=0.2 , etc.

One way is to do this:

list_a<-vector("list",number_of_vectors) and then set each list item using

list_a[[i]]<-c(list_a[[i]],num_to_push_back); etc for each i .

You can grow the vectors in the list - but it is not really advisable to grow things in R ...

Then you can do list_a[[a]][b] for your array. But the syntax is tragic, and I bet the performance will be slower than Jackson on propofol.

Another, more "R-idiomatic" way to avoid the use of ragged arrays might be to pre-allocate (or create/whatever) a matrix with dimensions larger than the length of your largest vector. The missing values of shorter vectors could be populated with NA - many/most functionality in R is designed to cope with NA . Or simply use the function na.omit when using the vectors. For instance

Not_a_ragged_array=matrix(NA,10,10) #a 10 by 10 matrix filled with NAs
#fill each column with a vector of random numbers, of random length 
num_rows=sample.int(9,10,replace=TRUE); for(i in 1:10){Not_a_ragged_array[1:num_rows[i],i]=rbinom(num_rows[i],10,0.8)}
Not_a_ragged_array
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,]    8    9    7    8    7   10    8    7    9     9
# [2,]    8   10   NA    6    8    9    8   NA    8     6
# [3,]    7    7   NA   10    7    9    9   NA    9     9
# [4,]   NA    9   NA    6   10    7   NA   NA    6     9
# [5,]   NA    5   NA    9    7    6   NA   NA   NA     9
# [6,]   NA    8   NA    9    9   NA   NA   NA   NA     8
# [7,]   NA   NA   NA    9   NA   NA   NA   NA   NA     9
# [8,]   NA   NA   NA    8   NA   NA   NA   NA   NA     8
# [9,]   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA
#[10,]   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA

as.vector(na.omit(Not_a_ragged_array[,1])) #get individual vectors like this
#[1] 8 8 7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM