我有一个矩阵(其价值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"
Run Code Online (Sandbox Code Playgroud)
我需要将它转换为这样的矩阵:
[,1] [,2]
[1,] FALSE FALSE
[2,] TRUE TRUE
[3,] TRUE TRUE
[4,] TRUE TRUE
Run Code Online (Sandbox Code Playgroud)
as.logical输出NAs为"字符数字"值,而as.numeric输出NAs为"字符逻辑"值.
我找到了一个解决方案,但我认为我遗漏了一些明显的立即转换:
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] …Run Code Online (Sandbox Code Playgroud) fa <- function(x){x+1}
fb <- function(x){x-1}
f1 <- function(x, y){f(x)^y}
f2 <- function(x, ab, y){
if(ab == 'a'){
f <- fa
} else {
f <- fb
}
f1(x, y)
}
f2(0, 'a', .5)
Error in f1(x, y) : could not find function "f"
Run Code Online (Sandbox Code Playgroud)
上述方法不起作用,因为f未在f1环境中定义.
什么是使这项工作的好方法?那
f2环境中f2(这将是一个麻烦,并创建复制/粘贴错误的机会)定义某种"亚全球"环境,并将我希望每个人都在这个环境中使用的东西放在一起,然后让每个函数都能够从"subglobal"访问它们是否有意义?然后以某种方式确保subglobal始终是全球的严格子集?如果明智,我该怎么做?