R和rbind使没有相同长度的条目为零 [英] R and rbind making entries without the same length be zero

查看:80
本文介绍了R和rbind使没有相同长度的条目为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有两个向量v1v2,我想调用rbind(v1, v2).但是,假定为length(v1)> length(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(sapply(v, length))
do.call(rbind, lapply(v, `[`, seq_len(n)))

这篇关于R和rbind使没有相同长度的条目为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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