在 R 中不同时间复制向量中的每个元素 [英] Replicate each element in a vector different times in R

查看:22
本文介绍了在 R 中不同时间复制向量中的每个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数字向量 v

Suppose I have a numeric vector v

v <- 1:5

我想代表

v[1]v[1] 次.

v[2] 乘以 v[2] 次...依此类推....

v[2] by v[2] times... and so on....

所需的输出是:

1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 

以下不起作用.有什么想法吗?

The following does not work. Got any ideas?

rep(v, each = function(x) v[x]) 

非常感谢.

推荐答案

我们可以对自己使用rep

rep(v, v)

如果我们想指定参数,使用times

If we want to specify the argument, use times

rep(v, times = v)

each 不需要匿名函数,它只需要一个长度为 1 的向量.根据 ?rep

The each would not take anonymous function and it takes only a vector of length 1. According to ?rep

each - 非负整数.x 的每个元素每次都重复.其他输入将被强制为整数或双向量并采用第一个元素.如果不适用或无效,则视为 1.

each - non-negative integer. Each element of x is repeated each times. Other inputs will be coerced to an integer or double vector and the first element taken. Treated as 1 if NA or invalid.

这篇关于在 R 中不同时间复制向量中的每个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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