I am trying to use mapvalues to rename a long list of levels of a factor. As it seemed not to be working correctly, I produced a simple example showing the issue.
x <- c("a", "b", "c","c","d","a")
y <- c("a", "c", "c","d","d","b")
z<-data.frame(cbind(x,y))
levels(z$y)<-mapvalues(z$y, c("a", "c","b"), c("A", "C","m"))
levels(z$x)<-mapvalues(z$x, c("a", "c","b"), c("A", "C","m"))
>z
x y
1 A A
2 m C
3 C C
4 C d
5 C d
6 A C
As can be seen, $x[5]
should be "d" and $y[6]
should be "m". I also tried applying "as.character" to "from" "to" vectors but it didn't work either. I'm working in RStudio, Mac version, R version 3.5.2 (2018-12-20) -- "Eggshell Igloo". Thanks for help.
If we look at the output of
plyr::mapvalues(z$y, c("a", "c","b"), c("A", "C","m"))
#[1] A C C d d m
#Levels: A m C d
It is a vector with the same length as 'x', while the levels
length is different
If we assign this output to the levels(z$y
)`, there is length difference. We can either do the assignment to the whole column
z$y <- plyr::mapvalues(z$y, c("a", "c","b"), c("A", "C","m"))
Or change the levels
with the corresponding levels
levels(z$y) <- levels(plyr::mapvalues(z$y, c("a", "c","b"), c("A", "C","m")))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.