不同长度的 rbind 向量:填充零(或 NA)而不是回收 [英] rbind vectors of different length: pad with zero (or NA) instead of recycling

查看:50
本文介绍了不同长度的 rbind 向量:填充零(或 NA)而不是回收的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个向量 v1v2 并且我想调用 rbind(v1, v2).但是,假设 length(v1) >长度(v2).从我读过的文档中,较短的向量将被回收.以下是此回收"的示例:

Say I have two vectors v1 and v2 and that I want to call rbind(v1, v2). However, supposed length(v1) > length(v2). From the documentation I have read that the shorter vector will be recycled. Here is an example of this "recycling":

v1 <- c(1, 2, 3, 4, 8, 5, 3, 11)
v2 <- c(9, 5, 2)
rbind(v1, v2)
#    [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
# v1    1    2    3    4    8    5    3   11
# v2    9    5    2    9    5    2    9    5

  1. 有什么简单的方法可以阻止 v2 被回收,而是将剩余的条目设为 0?
  2. 有没有更好的方法来构建向量和矩阵?
  1. Is there any straightforward way I can stop v2 from being recycled and instead make the remaining entries 0?
  2. Is there a better way to build vectors and matrices?

非常感谢所有帮助!

推荐答案

使用以下内容:

rbind(v1, v2=v2[seq(v1)])

   [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
v1    1    2    3    4    8    5    3   11
v2    9    5    2   NA   NA   NA   NA   NA


为什么有效:通过大于其长度的值对向量进行索引会返回该索引点处的 NA 值.


Why it works: Indexing a vector by a value larger than its length returns a value of NA at that index point.

 #eg: 
{1:3}[c(3,5,1)]
#[1]  3 NA  1

因此,如果你用较长的索引索引较短的,你将得到较短的所有值加上一系列NA

Thus, if you index the shorter one by the indecies of the longer one, you willl get all of the values of the shorter one plus a series of NA's

概括:

v <- list(v1, v2)
n <- max(lengths(v))
# same:
# n <- max(sapply(v, length))
do.call(rbind, lapply(v, `[`, seq_len(n)))

这篇关于不同长度的 rbind 向量:填充零(或 NA)而不是回收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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