我有一个矩阵(具有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
有什么建议么?