仅对某些情况添加值

Add a value only to certain cases

我有一个数据框:

x <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
y <- c(2, 2, 2, 0, 0, 0, 0, 0, 2, 2,  2, 2, 2, 2, 2, 2, 2, 2, 2, 2)
df <- data.frame(x, y)

现在我想更改 x 中的值,但仅当 y 等于 2 时更改 x 中所有值的 10%。例如

set.seed(999)
df[sample(which(df$y == 2), round(0.1 * length(which(df$y == 2)))), ]

     x y
 11 11 2
 14 14 2

对于这种情况,我想添加 + 1000。结果应该如下所示:

     x    y
 1   1    2
 2   2    2
 3   3    2
 4   4    0
 5   5    0
 6   6    0
 7   7    0
 8   8    0
 9   9    2
 10 10    2
 11 1011  2
 12 12    2
 13 13    2
 14 1014  2
 15 15    2
 16 16    2
 17 17    2
 18 18    2
 19 19    2
 20 20    2

我可以编辑子样本,但我不知道如何以简洁的方式将结果添加到数据框 "df"。我很感激任何帮助!

使用 base R 的一种简单方法可能是

#Get indices when y = 2
inds <- df$y == 2

#set.seed(123)
#Get random indices whose value you need to change
inds_to_change <- sample(which(inds), round(0.1 * sum(inds)))

#Change the value
df$x[inds_to_change] <- df$x[inds_to_change] + 1000

df
#      x y
#1     1 2
#2     2 2
#3     3 2
#4     4 0
#5     5 0
#6     6 0
#7     7 0
#8     8 0
#9     9 2
#10 1010 2
#11   11 2
#12   12 2
#13   13 2
#14   14 2
#15   15 2
#16   16 2
#17 1017 2
#18   18 2
#19   19 2
#20   20 2