9

我有一个矩阵(具有class character像这样的值:

mat <- matrix(c("0", "TRUE", "1", "2",
                "FALSE", "TRUE", "TRUE", "2"), nrow = 4, ncol = 2)
#> mat
#     [,1]   [,2]   
#[1,] "0"    "FALSE"
#[2,] "TRUE" "TRUE" 
#[3,] "1"    "TRUE" 
#[4,] "2"    "2"  

我需要将它转换为这样的矩阵:

      [,1]  [,2]
[1,] FALSE FALSE
[2,]  TRUE  TRUE
[3,]  TRUE  TRUE
[4,]  TRUE  TRUE

as.logical将 s输出NA到“字符数字”值,而将 sas.numeric输出NA到“字符逻辑”值。

我找到了一个解决方案,但我认为我遗漏了一些关于立即转换的明显内容:

new_mat2 <- array(as.numeric(mat), dim(mat))
new_mat <- array(as.logical(mat), dim(mat))

new_mat[is.na(new_mat)] <- new_mat2[is.na(new_mat)]
mat2 <- array(as.logical(new_mat), dim(new_mat))

#> mat2
#      [,1]  [,2]
#[1,] FALSE FALSE
#[2,]  TRUE  TRUE
#[3,]  TRUE  TRUE
#[4,]  TRUE  TRUE

有什么建议么?

4

4 回答 4

16

试试这个:

> mat[,] <- ifelse(mat %in% c("0", "FALSE"), FALSE, TRUE) # pay attention to @Señor O comment to shorten this step.
> mat
     [,1]    [,2]   
[1,] "FALSE" "FALSE"
[2,] "TRUE"  "TRUE" 
[3,] "TRUE"  "TRUE" 
[4,] "TRUE"  "TRUE" 

如果你想mat成为一个由逻辑值组成的data.frame,那么:

> mat <- sapply(as.data.frame(mat), as.logical)
> mat
        V1    V2
[1,] FALSE FALSE
[2,]  TRUE  TRUE
[3,]  TRUE  TRUE
[4,]  TRUE  TRUE
> sapply(mat, class)  # checking class
[1] "logical" "logical" "logical" "logical" "logical" "logical" "logical" "logical"
于 2013-10-24T15:03:04.047 回答
3

NA是一个逻辑常数,因此它具有它必须遵守的真值表定律。我们可以利用这些来做...

mat2 <- as.logical(mat) & ( as.integer(mat) > 0 )
mat2[is.na(mat2)] <- TRUE
dim(mat2) <- dim(mat)
#      [,1]  [,2]
#[1,] FALSE FALSE
#[2,]  TRUE  TRUE
#[3,]  TRUE  TRUE
#[4,]  TRUE  TRUE

在您没有NA原始矩阵时才有效,因为我们依赖于NA自身是一个逻辑常数。如果一个给定的值是FALSEas.logical将评估为TRUE,但也不能 ( &) 是as.integer,所以将给出FALSE。If it is"0" as.logical将评估为NA,whileas.integer > 0将评估为FALSENA&FALSE评估为FALSE. 满足两个 FALSE 条件,因此剩下的NA 必须TRUE

于 2013-10-24T15:29:32.433 回答
3

垫子!=“0”和垫子!=“假”

> mat
     [,1]   [,2]   
[1,] "0"    "FALSE"
[2,] "TRUE" "TRUE" 
[3,] "1"    "TRUE" 
[4,] "2"    "2"    

> mat != "0" & mat != "FALSE"
      [,1]  [,2]
[1,] FALSE FALSE
[2,]  TRUE  TRUE
[3,]  TRUE  TRUE
[4,]  TRUE  TRUE
于 2014-03-17T23:45:33.090 回答
0

我知道的最直接的是:

as.numeric(factor(matrix))

其中'matrix'是我们要更改为数字的矩阵的名称

于 2014-11-11T11:39:27.780 回答