我不是R的新手用户,但以下内容最令人困惑。
我有一个数据框(尽管问题同样存在于矩阵中),分类变量的值为+ 1 / -1,我想将其转换为因子。
mat <- matrix(sample(c(-1, +1), 16, replace = T), nrow = 4)
mat <- data.frame(mat)
然而,使用
mat <- apply(mat, 2, factor)
将整数转换为字符而不是因子:
> mat
[,1] [,2] [,3] [,4]
[1,] "-1" "1" "-1" "1"
[2,] "-1" "-1" "-1" "-1"
[3,] "-1" "1" "1" "1"
[4,] "-1" "-1" "1" "1"
也许是以同样的方式(我有一些与其他数据有关的问题)尝试将矩阵和数据框中的字符名称转换为因子会导致更混乱的行为:
mat2 <- matrix(sample(letters, 16, replace = T), nrow = 4)
> mat2
[,1] [,2] [,3] [,4]
[1,] "x" "m" "r" "e"
[2,] "u" "r" "b" "p"
[3,] "j" "p" "h" "j"
[4,] "k" "s" "e" "x"
mat2[,1] <- factor(mat2[,1])
> mat2
[,1] [,2] [,3] [,4]
[1,] "4" "m" "r" "e"
[2,] "3" "r" "b" "p"
[3,] "1" "p" "h" "j"
[4,] "2" "s" "e" "x"
任何帮助或澄清将不胜感激。
答案 0 :(得分:2)
永远记住数据框是列表,因此对列进行操作就像迭代列表的元素一样。我想也许你打算做更像这样的事情:
mat[] <- lapply(mat,factor)
或者这个:
as.data.frame(lapply(mat,factor))
虽然在这里,但请注意每个因素的水平不一样!