Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
以10%的概率测试逻辑和if FALSE是否更改为TRUE_R_Logical Operators - Fatal编程技术网

以10%的概率测试逻辑和if FALSE是否更改为TRUE

以10%的概率测试逻辑和if FALSE是否更改为TRUE,r,logical-operators,R,Logical Operators,我试图计算data.frame中的单个(逻辑)列,如果有FALSE,则将其转换为TRUE,但概率为10%。我想我需要的功能是 as.logical(rbinom(1, 1, 0.1)) 我试图使用lappy将其应用于列,但我无法获得正确的布尔语法。例如,使用以下df df <- data.frame (NM =c("N1", "N2", "N3", NA), D1 = c(TRUE,FALSE,TRUE,NA), D

我试图计算data.frame中的单个(逻辑)列,如果有FALSE,则将其转换为TRUE,但概率为10%。我想我需要的功能是

as.logical(rbinom(1, 1, 0.1))
我试图使用lappy将其应用于列,但我无法获得正确的布尔语法。例如,使用以下df

df <- data.frame (NM =c("N1", "N2", "N3", NA),
                  D1 = c(TRUE,FALSE,TRUE,NA),
                  D2 = c(100L,130L,140L,NA),
                  D3 = c(0.5, 1, 0, NA),
                  D4 = c(20, 24, 28, NA),
                  D5 = c(FALSE, FALSE, FALSE, NA)
                  )

但它对我来说并不正常。

这里有一个解决方案。首先,我们得到
D1
中与
FALSE
对应的所有行号

(index <- which(!is.na(df$D1) & !df$D1))
## [1] 2
顺便说一句,代码是矢量化的:我们一次将此过程应用于所有
FALSE
s。这可以通过以下内容来说明:

x <- c(TRUE, rep(FALSE, 20), NA) # an exemplary vector
(index <- which(!is.na(x) & !x))
##  [1]  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21
x[index] <- sample(c(TRUE, FALSE), length(index),
                   replace=TRUE, prob=c(0.1, 0.9))
x
## [1]  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [18] FALSE  TRUE FALSE FALSE    NA

x这里有一个解决方案。首先,我们得到
D1
中与
FALSE
对应的所有行号

(index <- which(!is.na(df$D1) & !df$D1))
## [1] 2
顺便说一句,代码是矢量化的:我们一次将此过程应用于所有
FALSE
s。这可以通过以下内容来说明:

x <- c(TRUE, rep(FALSE, 20), NA) # an exemplary vector
(index <- which(!is.na(x) & !x))
##  [1]  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21
x[index] <- sample(c(TRUE, FALSE), length(index),
                   replace=TRUE, prob=c(0.1, 0.9))
x
## [1]  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [18] FALSE  TRUE FALSE FALSE    NA
x