从列表创建一个数组,每个值具有不同数量的输出 [英] Create an array from a list with different number of outputs for each value

查看:56
本文介绍了从列表创建一个数组,每个值具有不同数量的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从一个列表中创建一个数组,该列表针对从函数获得的每个值具有不同数量的输出。

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,simple ='array')

这些是输出。

> list_i1 [[1]]
[1] 86101

> list_i1 [[2]]
[1] 35 61112

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

由于某些值具有更多2输出数字,而有些数字为3,我无法从以下列表中创建数组。理想情况下,我希望插槽中的零不被数组中的第三个输出填充,以便看起来像这样:

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

推荐答案

我使用了此处此处

重新创建示例:

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

将所有NA替换为所需的0:

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

我真的很想用某种 apply替换for循环,但无法弄清楚。如果有人知道如何不使用for循环,我想看看!

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!

这篇关于从列表创建一个数组,每个值具有不同数量的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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