Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

r - Create an array from a list with different number of outputs for each value

I am trying to create an array out of a list with different numbers of outputs for each value that I obtained from a function.

This is the code I am using:

list_i1 = sapply(implicit$image_1_id, num, simplify = 'array')

And these are the outputs.

> list_i1[[1]] [1] 86 101

> list_i1[[2]] [1] 35 61 112

> list_i1[[3]] [1] 10 15

Due to the fact that some of the values have more 2 output numbers whereas some have 3, I am unable to create an array from the following list. Ideally, I would like to have a zero in the slot that isn't filled by a third output within the array so as to look like this:

1 86 35 10 2 101 61 15 3 0 112 0

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I came up with a very similar solution to @Fernandes, using tips from here and here

Recreate your example:

lst <- list(c(86, 101), c(35, 61, 112), c(10, 15))
# [[1]]
# [1]  86 101
# 
# [[2]]
# [1]  35  61 112
# 
# [[3]]
# [1] 10 15

Figure out the number of rows needed, and then extend each of the vectors to that length:

num_row <- max(sapply(lst, length))
for (i in seq_along(lst)) {
  length(lst[[i]]) <- num_row
} 
# [[1]]
# [1]  86 101  NA
# 
# [[2]]
# [1]  35  61 112
# 
# [[3]]
# [1] 10 15 NA

Column bind all the now-equal-length-vectors together into a matrix:

m <- sapply(lst, cbind)
#      [,1] [,2] [,3]
# [1,]   86   35   10
# [2,]  101   61   15
# [3,]   NA  112   NA

Replace all the NA's with the desired 0's:

m[is.na(m)] <- 0
#      [,1] [,2] [,3]
# [1,]   86   35   10
# [2,]  101   61   15
# [3,]    0  112    0

I really wanted to replace the for loop with with some kind of 'apply', but couldn't figure it out. If anyone knows how to not use the for loop, I'd like to see it!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...