mapvalues in plyr gives unexpected output when “to” argument is a factor…is it a bug?

江枫思渺然 提交于 2019-12-13 00:34:38

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!