简体   繁体   English

如何在R中的列表中组合不同长度的向量?

[英]how to combine vectors with different length within a list in 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")

which gives the following list: 给出以下列表:

>x
>[[1]]
>species.A species.C 
>         1         4 
>[[2]]
>species.A species.B species.C 
>        3        19        11

combining them using the do.call function: y<- do.call(cbind,x) 使用do.call函数组合它们: y<- do.call(cbind,x)

gives: 得到:

>y
>             [,1] [,2]
>   species.A    1    3
>   species.B    4   19
>   species.C    1   11

while I would like to obtain this: 虽然我想获得这个:

>             [,1] [,2]
>   species.A    1    3
>   species.B   NA   19
>   species.C    4   11

You need to give R a bit more help, by first preparing the particular vectors, all of the same length, that you eventually want to cbind together. 你需要给R一点帮助,首先准备你最终想要cbind在一起的所有相同长度的特定向量。 Otherwise (as you've seen) R uses its usual recycling rules to fill out the matrix. 否则(正如您所见)R使用其通常的回收规则来填写矩阵。

Try something like this: 尝试这样的事情:

spp <- paste("species", c("A", "B", "C"), sep=".")

x2 <- lapply(x, FUN=function(X) X[spp])
mat <- do.call("cbind", x2)
row.names(mat) <- spp

mat
          [,1] [,2]
species.A    1    3
species.B   NA   19
species.C    4   11

EDIT : As Brian mentions in comments, this could be made a bit more compact (but at the expense of some readability). 编辑 :正如布莱恩在评论中提到的那样,这可以做得更紧凑(但是以牺牲一些可读性为代价)。 Which one you use is just a matter of taste: 你使用哪一个只是一个品味问题:

mat <- do.call("cbind", lapply(x, "[", spp))
row.names(mat) <- spp

It looks like you're actually trying to do a merge. 看起来你真的想要合并。 As such, merge will work. 因此, merge将起作用。 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.) (这将创建一个数据框而不是矩阵,但对于大多数目的来说,这应该不是问题。)

merge(x = x[[1]], y = x[[2]], by = "names", all.y = TRUE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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