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
427 views
in Technique[技术] by (71.8m points)

r - typeof returns integer for something that is clearly a factor

Create a variable:

a_variable <- c("a","b","c")

Check type:

typeof(a_variable)

I want a factor - change to factor:

a_variable <- as.factor(a_variable)

Check type:

typeof(a_variable)

Says that it's integer!? As an R newb, this is confusing. I just told R to make a factor not an integer.

Test to see if it somehow magically did create an integer:

a_variable * 1

Hmm... I get an error message saying "*" isn't meaningful for factors. This seems weird to me since R just told me it was an integer!?

Clearly it's me who is confused, can someone more enlightened help make sense of this madness for me?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This is a language feature that confused me as well in my early days of R programming. The typeof function is giving information that's at a "lower" level of abstraction. Factor variables (and also Dates) are stored as integers. Learn to use class or str rather than typeof (or mode). They give more useful information. You can look at the full "structure" of a factor variable with dput:

 dput( factor( rep( letters[1:5], 2) ) )
# structure(c(1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L), 
            .Label = c("a", "b", "c", "d", "e"), class = "factor")

The character values that are usually thought of as the factor values are actually stored in an attribute (which is what "levels" returns), while the "main" part of the variable is a set of integer indices pointing to teh various level "attributes), named .Label, so mode returns "numeric" and typeof returns "integer". For this reason one usually needs to use as.character that will coerce to what most people think of as factors, namely their character representations.


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

...