mode(B) <- "logical"
或 "mode<-"(B, "logical")
。我们还可以使用storage.mode
函数。
这个解决方法有两个好处:
- 代码更易读;
- 逻辑在一般情况下都可行(见下面的示例)。
我在阅读一些带有编译代码包的源代码时学到了这个技巧。当将 R 数据结构传递给 C 或 FORTRAN 函数时,可能需要进行某些类型强制转换,它们通常使用 mode
或 storage.mode
来实现。这两个函数都保留 R 对象的属性,如矩阵的 "dim" 和 "dimnames"。
A <- matrix(1:4, nrow = 2, dimnames = list(letters[1:2], LETTERS[1:2]))
"mode<-"(A, "numeric")
"mode<-"(A, "logical")
"mode<-"(A, "chracter")
"mode<-"(A, "complex")
str("mode<-"(A, "list"))
请注意,模式更改仅适用于向量的合法模式(请参见
?vector
)。在R中有许多模式,但只有一些模式适用于向量。我在
我的这个答案中涵盖了这一点。
另外,“因子”不是向量(请参见
?vector
),因此您无法对因子变量进行模式更改。
f <- factor(c("a", "b"))
## this "surprisingly" doesn't work
mode(f) <- "character"
#Error in `mode<-`(`*tmp*`, value = "character") :
# invalid to change the storage mode of a factor
## this also doesn't work
mode(f) <- "numeric"
#Error in `mode<-`(`*tmp*`, value = "numeric") :
# invalid to change the storage mode of a factor
## this does not give any error but also does not change anything
## because a factor variable is internally coded as integer with "factor" class
mode(f) <- "integer"
f
#[1] a b
#Levels: a b