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

编程入门 行业动态 更新时间:2024-10-06 12:29:51
本文介绍了如何在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中的列表中合并具有不同长度的向量?

本文发布于:2023-11-29 15:36:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646815.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:向量   长度   如何在   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!