对不起,我觉得我原来的答案写得不好。为什么我在一开始就提出了“因素矩阵”?这是一个更好的尝试。
来自?apply:
If ‘X’ is not an array but an object of a class with a non-null
‘dim’ value (such as a data frame), ‘apply’ attempts to coerce it
to an array via ‘as.matrix’ if it is two-dimensional (e.g., a data
frame) or via ‘as.array’.
因此,as.matrix 将数据框转换为矩阵,然后将FUN 按行或按列应用。
来自?as.matrix:
‘as.matrix’ is a generic function. The method for data frames
will return a character matrix if there is only atomic columns and
any non-(numeric/logical/complex) column, applying ‘as.vector’ to
factors and ‘format’ to other non-character columns. Otherwise,
the usual coercion hierarchy (logical < integer < double <
complex) will be used, e.g., all-logical data frames will be
coerced to a logical matrix, mixed logical-integer will give a
integer matrix, etc.
The default method for ‘as.matrix’ calls ‘as.vector(x)’, and hence
e.g. coerces factors to character vectors.
我不是以英语为母语的人,我无法阅读以下内容(这看起来很重要!)。有人可以澄清一下吗?
如果只有原子列和任何非(数字/逻辑/复杂)列,则数据框的方法将返回字符矩阵,将“as.vector”应用于因子,将“格式”应用于其他非字符列.
来自?as.vector:
Note that factors are _not_ vectors; ‘is.vector’ returns ‘FALSE’
and ‘as.vector’ converts a factor to a character vector for ‘mode
= "any"’.
简单地说,只要你在数据框中有一个因子列,as.matrix 就会给你一个字符矩阵。
我相信这个带有数据框问题的apply 已经被多次提出,上面只是添加了另一个重复的答案。真对不起。我没有仔细阅读OP的问题。首先让我感到震惊的是,R 无法构建真正的因子矩阵。
f <- factor(letters[1:4])
matrix(f, 2, 2)
# [,1] [,2]
#[1,] "a" "c"
#[2,] "b" "d"
## a sneaky way to get a matrix of factors by setting `dim` attribute
dim(f) <- c(2, 2)
# [,1] [,2]
#[1,] a c
#[2,] b d
#Levels: a b c d
is.matrix(f)
#[1] TRUE
class(f)
#[1] "factor" ## not a true matrix with "matrix" class
虽然这很有趣,但它应该与 OP 的问题不太相关。
再次抱歉在这里弄得一团糟。太惨了!!
如果我这样做sapply 会有帮助吗?因为我有很多列需要转换为因子。
实际使用lapply。 sapply 会将结果简化为一个数组,即二维情况下的矩阵。这是一个例子:
dat <- head(trees)
sapply(dat, as.factor)
# Girth Height Volume
#[1,] "8.3" "70" "10.3"
#[2,] "8.6" "65" "10.3"
#[3,] "8.8" "63" "10.2"
#[4,] "10.5" "72" "16.4"
#[5,] "10.7" "81" "18.8"
#[6,] "10.8" "83" "19.7"
new_dat <- data.frame(lapply(dat, as.factor))
str(new_dat)
#'data.frame': 6 obs. of 3 variables:
# $ Girth : Factor w/ 6 levels "8.3","8.6","8.8",..: 1 2 3 4 5 6
# $ Height: Factor w/ 6 levels "63","65","70",..: 3 2 1 4 5 6
# $ Volume: Factor w/ 5 levels "10.2","10.3",..: 2 2 1 3 4 5
sapply(new_dat, class)
# Girth Height Volume
#"factor" "factor" "factor"
apply(new_dat, 2, class)
# Girth Height Volume
#"character" "character" "character"
关于typeof,因子实际上存储为整数。
sapply(new_dat, typeof)
# Girth Height Volume
#"integer" "integer" "integer"
当您dput 时,您可以看到这一点。例如:
dput(new_dat[[1]])
#structure(1:6, .Label = c("8.3", "8.6", "8.8", "10.5", "10.7",
#"10.8"), class = "factor")
实际值为1:6。角色等级只是一个属性。