r - 将随机值添加到向量中的随机 block

标签 r vector random

我有一个数字向量

vect <- c(0,16,11,132,0,0,0,18,28,245,0,0,55,45,19,30,20,0,0,0,12,0)

有四个系列的值不等于零。

(16,11,132), (18,28,245), (55,45,19,30,20), (12)

对于随机选择的 1/4 系列(一个系列),我想添加一个介于 -10 和 10 之间的随机整数值。

例如,如果选择的系列是第二个并且选择的值是-5,那么结果将是

vect2 <- c(0,16,11,132,0,0,0,13,23,240,0,0,55,45,19,30,20,0,0,0,12,0)

这是一个只有一行的例子,该函数将应用于整个矩阵

最佳答案

以下不是很优雅的代码,应该可以工作。它使用 rle

set.seed(1)
vect <- c(0,16,11,132,0,0,0,18,28,245,0,0,55,45,19,30,20,0,0,0,12,0)

# Get non-zero runs
runs <- rle(vect!=0)
non_zero_runs <- with(runs, lengths[values])

# Sample the required
rand_run <- sample(seq_along(non_zero_runs), size = 1)
print(rand_run)
#[1] 2
rand_int <- sample(-10:10, size = 1)
print(rand_int)
#[1] -3

# Identify the sampled run
which_run <- min(which(cumsum(runs$values) == rand_run))

# Identify the corresponding indices
start <- sum(runs$lengths[seq_len(which_run - 1)]) + 1
end <- start + runs$lengths[which_run] - 1

vect[start:end] <- vect[start:end] + rand_int
print(vect)
#[1]   0  16  11 132   0   0   0  15  25 242   0   0  55  45  19  30  20   0   0   0  12   0

您可以尝试自己减少代码。代码非常冗长,因为它是解决和理解问题的一部分。

关于r - 将随机值添加到向量中的随机 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53949579/

相关文章:

r - %like% 在 r 中有多个模式

c++ - findContours 在 OpenCV 中崩溃编译器

C++ 在使用 min_element 或 max_element 时检索 vector 中的索引值

jQuery 从给定列表中获取随机颜色

r - 插入符号中使用预处理的数据插补返回的观察结果少于预期

r - ddply 用于没有组的整个数据?

r - 如何在 ggplot map 上添加地理空间连接?

c++ - 在 C++ 中使用 vector 的通用列表

java - 从java中的各个位构造一个字节

random - 对于大型数据库,从 Impala 采样的最佳查询是什么?