合并(合并)不同长度的向量 [英] Combining (cbind) vectors of different length

查看:137
本文介绍了合并(合并)不同长度的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个长度不等的向量,我想cbind.我将向量放入列表中,并尝试结合使用do.call(cbind, ...):

I have several vectors of unequal length and I would like to cbind them. I've put the vectors into a list and I have tried to combine the using do.call(cbind, ...):

nm <- list(1:8, 3:8, 1:5)
do.call(cbind, nm)

#      [,1] [,2] [,3]
# [1,]    1    3    1
# [2,]    2    4    2
# [3,]    3    5    3
# [4,]    4    6    4
# [5,]    5    7    5
# [6,]    6    8    1
# [7,]    7    3    2
# [8,]    8    4    3
# Warning message:
#   In (function (..., deparse.level = 1)  :
#         number of rows of result is not a multiple of vector length (arg 2)

正如预期的那样,结果矩阵中的行数是最长向量的长度,而较短向量的值将被回收以弥补长度.

As expected, the number of rows in the resulting matrix is the length of the longest vector, and the values of the shorter vectors are recycled to make up for the length.

相反,我想用NA值填充较短的向量,以获得与最长向量相同的长度.我希望矩阵看起来像这样:

Instead I'd like to pad the shorter vectors with NA values to obtain the same length as the longest vector. I'd like the matrix to look like this:

#      [,1] [,2] [,3]
# [1,]    1    3    1
# [2,]    2    4    2
# [3,]    3    5    3
# [4,]    4    6    4
# [5,]    5    7    5
# [6,]    6    8    NA
# [7,]    7    NA   NA
# [8,]    8    NA   NA

我该怎么做?

推荐答案

可以使用索引,如果索引的数字超出对象的大小,它将返回NA.这适用于用foo定义的任意数量的行:

You can use indexing, if you index a number beyond the size of the object it returns NA. This works for any arbitrary number of rows defined with foo:

nm <- list(1:8,3:8,1:5)

foo <- 8

sapply(nm, '[', 1:foo)

或者在一行中使用最大的向量作为行数:

Or in one line using the largest vector as number of rows:

sapply(nm, '[', seq(max(sapply(nm,length))))

R 3.2.0中,您可以使用lengths(获取列表中每个元素的长度")代替sapply(nm, length):

From R 3.2.0 you may use lengths ("get the length of each element of a list") instead of sapply(nm, length):

sapply(nm, '[', seq(max(lengths(nm))))

这篇关于合并(合并)不同长度的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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