Home > other >  Change 0/1 values to TRUE/FALSE in R
Change 0/1 values to TRUE/FALSE in R

Time:10-21

I have a matrix in R

x1 = matrix(c(1,0,1,1),2,2)

for which I want to change the values 1 to TRUE and 0 to FALSE, I thought that the following code would work

for(i in 1:2){
 for(j in 1:2){
   if(x1[i,j]==1){
       x1[i,j] = TRUE
   }else{
       x1[i,j] = FALSE
   }
  }
}

But it doesn't, is there a way to change the 0/1 values of matrix to TRUE/FALSE ??

CodePudding user response:

Use x1 == 1:

> x1 == 1
      [,1] [,2]
[1,]  TRUE TRUE
[2,] FALSE TRUE
> 

Or use x1 == TRUE:

> x1 == TRUE
      [,1] [,2]
[1,]  TRUE TRUE
[2,] FALSE TRUE
> 

Or with apply and as.logical:

> apply(x1, 2, as.logical)
     [,1]  [,2]
[1,] TRUE FALSE
[2,] TRUE  TRUE
> 

CodePudding user response:

Here are a few alternatives. In the ones that use y1, it is first defined as a logical matrix to circumvent automatic coercion to numeric which occurs when you try to assign a logical to a numeric matrix.

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))
  •  Tags:  
  • r
  • Related