复制由其他向量确定的向量中的某些值 [英] Replicate certain values in vector determined by other vector

查看:147
本文介绍了复制由其他向量确定的向量中的某些值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个值的向量(例如1:10),并希望在其中重复某些值两次或更多次(由另一个向量确定)(例如c(3,4,6,8)).在此示例中,重复2次,结果将为c(1,2,3,3,4,4,5,6,6,7,8,8,9,10).

I have a vector of values (say 1:10), and want to repeat certain values in it 2 or more times, determined by another vector (say c(3,4,6,8)). In this example, the result would be c(1,2,3,3,4,4,5,6,6,7,8,8,9,10) when repeating 2 times.

这应适用于任意长度范围向量(如200:600),并且第二个向量包含在第一个向量中.有方便的方法可以实现这一目标吗?

This should work for an arbitrary length range vector (like 200:600), with a second vector which is contained by the first. Is there a handy way to achieve this?

推荐答案

Akrun的方法更紧凑,但这也可以

Akrun's is a more compact method, but this also will work

# get rep vector
reps <- rep(1L, 10L)
reps[c(3,4,6,8)] <- 2L

rep(1:10, reps)
 [1]  1  2  3  3  4  4  5  6  6  7  8  8  9 10

这里的见解是rep将在第二个参数中采用与第一个参数相同长度的整数矢量,该长度指示第一个参数中每个元素的重复次数.

The insight here is that rep will take an integer vector in the second argument the same length as the first argument that indicates the number of repetitions for each element of the first argument.

请注意,此解决方案基于c(3,4,6,8)是要重复的元素的索引或位置的假设.在这种情况下,则d-b的评论具有单线性

Note that this solution relies on the assumption that c(3,4,6,8) is the index or position of the elements that are to be repeated. Under this scenario, then d-b's comment has a one-liner

rep(x, (seq_along(x) %in% c(3,4,6,8)) + 1)

如果相反,c(3,4,6,8)表示要重复的值,则docendo-discimus的超紧凑代码,

If instead, c(3,4,6,8) indicates the values that are to be repeated, then docendo-discimus's super-compact code,

rep(x, (x %in% c(3,4,6,8)) * (n-1) +1)

其中,可以调整n来更改重复次数.如果您需要多次调用此函数,则可以将其汇总为类似

where n may be adjusted to change the number of repetitions. If you need to call this a couple times, this could be rolled up into a function like

myReps <- function(x, y, n) rep(x, (x %in% y) * (n-1) +1)

并称为

myReps(1:10, c(3,4,6,8), 2)

在当前情况下.

这篇关于复制由其他向量确定的向量中的某些值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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