Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

r - Unexpected conversion to chars instead of factors in data frames and matrices

I am not a novice user of R, but the following is most confusing.

I have a data frame (although the problem is equally present for matrices) of categorical variables taking the values +1/-1, which I'd like to convert into factors.

mat <- matrix(sample(c(-1, +1), 16, replace = T), nrow = 4)
mat <- data.frame(mat)

However, using

mat <- apply(mat, 2, factor)

turns integers into characters instead of factors:

> 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" 

Perhaps in the same vein (and I had a problem of this sort with some of my other data) trying to convert character names in matrices and data frames into factors results in more confusing behaviour:

 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" 

any help or clarification would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Always remember that data frames are lists, and so operating on columns is just like iterating over elements of a list. I think maybe you intended to do something more like this:

mat[] <- lapply(mat,factor)

or this:

as.data.frame(lapply(mat,factor))

Although even here, note that the levels of each factor are not the same!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...