我有一个数字向量
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/