如何在R中的列表中合并具有不同长度的向量? [英] how to combine vectors with different length within a list in R?
本文介绍了如何在R中的列表中合并具有不同长度的向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
合并列表中包含的以下向量时出现问题:
I have a problem when combining the following vectors included in the list:
x <- list(as.numeric(c(1,4)),as.numeric(c(3,19,11)))
names (x[[1]]) <- c("species.A","species.C")
names (x[[2]]) <- c("species.A","species.B","species.C")
给出以下列表:
>x
>[[1]]
>species.A species.C
> 1 4
>[[2]]
>species.A species.B species.C
> 3 19 11
使用do.call函数将它们组合:
y<- do.call(cbind,x)
combining them using the do.call function:
y<- do.call(cbind,x)
给予:
>y
> [,1] [,2]
> species.A 1 3
> species.B 4 19
> species.C 1 11
同时我想获得这个:
> [,1] [,2]
> species.A 1 3
> species.B NA 19
> species.C 4 11
推荐答案
似乎您实际上是在尝试进行合并.这样,merge
将起作用.您只需要告诉它合并名称,并保留所有行即可.
It looks like you're actually trying to do a merge. As such, merge
will work. You just have to tell it to merge on the names, and to keep all rows.
do.call(merge, c(x, by=0, all=TRUE)) # by=0 and by="row.names" are the same
(这将创建一个数据框,而不是一个矩阵,但对于大多数目的而言,这应该不是问题.)
(This will create a data frame rather than a matrix, but for most purposes that shouldn't be an issue.)
这篇关于如何在R中的列表中合并具有不同长度的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文