我在 R 中有一個矩陣
x1 = matrix(c(1,0,1,1),2,2)
我想將值 1 更改為 TRUE 并將 0 更改為 FALSE,我認為以下代碼會起作用
for(i in 1:2){
for(j in 1:2){
if(x1[i,j]==1){
x1[i,j] = TRUE
}else{
x1[i,j] = FALSE
}
}
}
但它沒有,有沒有辦法將矩陣的 0/1 值更改為 TRUE/FALSE ??
uj5u.com熱心網友回復:
使用x1 == 1:
> x1 == 1
[,1] [,2]
[1,] TRUE TRUE
[2,] FALSE TRUE
>
或使用x1 == TRUE:
> x1 == TRUE
[,1] [,2]
[1,] TRUE TRUE
[2,] FALSE TRUE
>
或與apply和as.logical:
> apply(x1, 2, as.logical)
[,1] [,2]
[1,] TRUE FALSE
[2,] TRUE TRUE
>
uj5u.com熱心網友回復:
這里有一些替代方案。在使用 y1 的那些中,它首先被定義為一個邏輯矩陣,以規避當您嘗試為數字矩陣分配邏輯時發生的對數字的自動強制轉換。
x1 == 1
!!x1
apply(x1, 2, as.logical)
ifelse(x1, TRUE, FALSE)
array(as.logical(x1), dim(x1))
L <- as.logical(x1); ifelse(x1, L, L)
replace(array(dim = dim(x1)), TRUE, as.logical(x1))
y1 <- array(dim = dim(x1)) # x1 is input; y1 is output
y1[] <- as.logical(x1)
y1 <- array(dim = dim(x1)) # x1 is input; y1 is output
for(i in 1:nrow(x1)) {
for(j in 1:ncol(x1)) {
y1[i, j] <- x1[i, j] == 1
}
}
sapply(1:ncol(x1),
function(j) sapply(1:nrow(x1),
function(i) as.logical(x1[i, j])))
outer(1:nrow(x1), 1:ncol(x1),
Vectorize(function(i, j) as.logical(x1[i, j])))
library(listcompr)
gen.matrix(as.logical(x1[i, j]), i = 1:nrow(x1), j = 1:ncol(x1))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/326964.html
標籤:r
