问题
When I use mapvalues in the plyr package (plyr v1.8, R v2.15.1 Roasted Marshmallows), I get an odd result when the "to" argument is a factor. For example,
v1 = c(1,2,2,1,2)
mapvalues(v1, from = c(1, 2), to = factor( c('A', 'B') ) )
returns
[1] 1 2 2 1 2
instead of
[1] A B B A B
Levels: A B
To me it looks like it might be a bug, but I wanted to check with other people before bothering the developer. Is this a bug?
回答1:
This most likely isn't a bug. Factors are stored internally as integers. If you have a factor and want to map to the levels of the factor instead of the internal integer storage value you can call levels
on the factor first.
mapvalues(v1, from = c(1, 2), to = levels(factor(c('A', 'B'))))
If you want the result to be a factor then just call factor
on the result afterward.
回答2:
You need to remove the factor()
from mapvalues()
. Conversion to factor can be done after value replacement.
v1<-mapvalues(v1, from = c(1, 2), to = c('A', 'B'))
#Now convert to factor
v1<-as.factor(v1)
v1
[1] A B B A B
Levels: A B
来源:https://stackoverflow.com/questions/15516597/mapvalues-in-plyr-gives-unexpected-output-when-to-argument-is-a-factor-is-it