Add a random value to a random block in vector

Viewed 381

I have a numeric vector

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

There are four series of values not equal to zero.

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

For 1/4 of series (one serie) randomly choosed, I want to add a random integer value between -10 and 10.

For example, if the chosen serie is the second one and the chosen value is -5 the result will be

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

This is an example of only one row, the function will be applied to the entire matrix

3 Answers

The following not very elegant code, should work. It uses 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

You can try to reduce the code yourself. The code is very verbose as it was part of solving and understanding the issue.

Solution that doesn't use rle. Here I use diff to find positions that are not 0. Then randomly select one position and generate vector of zeroes except that one position.

# Extract positions that are not 0
sequences <- c(0, diff(vect != 0))

# Get starts
starts <- which(sequences == 1)
# One random position from starts
position <- sample(seq_along(starts), 1)

# Get absolute start and end positions
currentStart <- starts[position]
currentEnd <- which(sequences == -1)[position] - 1

# Add this vector to originak
addVector <- rep(0, length(vect))
addVector[currentStart:currentEnd] <- rep(sample(-10:10, 1), currentEnd - currentStart + 1)

vect + addVector

Here's a one-long-liner:

vect + with(rle(vect != 0), rep(replace(0 * values, which(values)[sample(sum(values), 1)], sample(-10:10, 1)), lengths))
# [1]   0  16  11 132   0   0   0  18  28 245   0   0  55  45  19  30  20   0   0   0   8   0

In more detail that would be

tmp <- rle(vect != 0)
add <- sample(-10:10, 1)
tmp$values <- replace(0 * tmp$val, which(tmp$val)[sample(sum(tmp$val), 1)], add)
vect + inverse.rle(tmp)

So, we construct a new vector by adding the second component to the initial vect. The part

replace(0 * tmp$val, which(tmp$val)[sample(sum(tmp$val), 1)], add)
# [1] 0 3 0 0 0 0 0 0 0

chooses one of the nonzero blocks and puts a new random value add there. Then

inverse.rle(tmp)
# [1] 0 3 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Related