我如何在R中使用矢量化来根据条件改变DF值?



假设我有以下DF:

<表类> C1 C2 tbody><<tr>00111100。。。。

您需要将nrow的值改为sample。试试这个方法-

set.seed(167814)
df[df$C1 == 1 & sample(0:5, nrow(df), replace = TRUE) < 2, ] <- 2
df
#   C1 C2
#1   0  0
#2   2  2
#3   2  2
#4   0  0
#5   1  1
#6   0  0
#7   2  2
#8   0  0
#9   1  1
#10  0  0
#11  1  1

这是一个完全矢量化的方法。创建逻辑索引index,如问题所示。然后在一次对sample的调用中抽样所有随机整数r。根据索引和条件r < 2的结合来替换。

x <- 'C1    C2
0   0
1   1
1   1
0   0'
df1 <- read.table(textConnection(x), header = TRUE)
set.seed(1)
index <- df1$C1 == 1
r <- sample(0:5, length(index), TRUE)
df1[index & r < 2, c("C1", "C2")] <- 2
df1
#>   C1 C2
#> 1  0  0
#> 2  1  1
#> 3  2  2
#> 4  0  0

在2022-05-11由reprex包(v2.0.1)创建

最新更新