如何将向量中的值复制到向量中的下一个位置 [英] How to copy a value in a vector to next position(s) in vector
本文介绍了如何将向量中的值复制到向量中的下一个位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的向量:
I have a vector that looks something like this:
c(0.5,0,0,0,0,0.7,0,0,0,0,0.4,0,0,0,0)
假设我想将位置 1、6 和 11(不为 0 的位置)上的值复制到该特定值之后的四个位置,以使向量看起来像这样:
Suppose I want to copy the values on positions 1, 6 and 11 (the ones that are not 0) to the four positions following that specific value, to make the vector look like this:
c(0.5,0.5,0.5,0.5,0.5,0.7,0.7,0.7,0.7,0.7,0.4,0.4,0.4,0.4,0.4)
在 R 中我怎样才能最好地做到这一点?
How could I best do that in R?
非常感谢!
推荐答案
我可能会使用 lapply
遍历每个大于 0 的元素,然后将 rep
函数应用于将这些值中的每一个重复 5 次并通过 do.call("c", ...)
合并结果列表条目.
I'd probably loop through every single element greater 0 using lapply
, then apply rep
function to repeat each of these values 5 times and merge the resulting list entries via do.call("c", ...)
.
do.call("c", lapply(which(tmp > 0), function(i) rep(tmp[i], 5)))
[1] 0.5 0.5 0.5 0.5 0.5 0.7 0.7 0.7 0.7 0.7 0.4 0.4 0.4 0.4 0.4
这篇关于如何将向量中的值复制到向量中的下一个位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文