In an answer to another question, @Marek posted the following solution: https://stackoverflow.com/a/10432263/636656
dat <- structure(list(product = c(11L, 11L, 9L, 9L, 6L, 1L, 11L, 5L,
7L, 11L, 5L, 11L, 4L, 3L, 10L, 7L, 10L, 5L, 9L, 8L)), .Names = "product", row.names = c(NA, -20L), class = "data.frame")
`levels<-`(
factor(dat$product),
list(Tylenol=1:3, Advil=4:6, Bayer=7:9, Generic=10:12)
)
Which produces as output:
[1] Generic Generic Bayer Bayer Advil Tylenol Generic Advil Bayer Generic Advil Generic Advil Tylenol
[15] Generic Bayer Generic Advil Bayer Bayer
This is just the printout of a vector, so to store it you can do the even more confusing:
res <- `levels<-`(
factor(dat$product),
list(Tylenol=1:3, Advil=4:6, Bayer=7:9, Generic=10:12)
)
Clearly this is some kind of call to the levels function, but I have no idea what's being done here. What is the term for this kind of sorcery, and how do I increase my magical ability in this domain?
names<-
and[<-
. – huonstructure(...)
construct instead of justdata.frame(product = c(11L, 11L, ..., 8L))
? (If there's some magic happening there, I'd like to wield it too!) – huon"levels<-"
function:function (x, value) .Primitive("levels<-")
, sort of likeX %in% Y
is an abbreviation for"%in%"(X, Y)
. – BenBarnes