[R] Reassign Multiple Factors to same Factor Value

arun smartpink111 at yahoo.com
Tue Mar 26 02:20:16 CET 2013


Hi,
You could also try:
library(plyr)
df1<- df
df2<- df
 df$y<-revalue(df$y,c("e"="others","f"="others","g"="others"))
df$y
#[1] a      b      c      d      others others others
#or
df1$y<-mapvalues(df1$y,from=c("e","f","g"),to=rep("others",3))
levels(df1$y)
#[1] "a"      "b"      "c"      "d"      "others"


#or
levels(df2$y)[match(c("e","f","g"),levels(df2$y))]<-"others"
 levels(df2$y)
#[1] "a"      "b"      "c"      "d"      "others"
A.K.





________________________________
From: Lorenzo Isella <lorenzo.isella at gmail.com>
To: "r-help at stat.math.ethz.ch" <r-help at stat.math.ethz.ch> 
Sent: Monday, March 25, 2013 6:18 PM
Subject: [R] Reassign Multiple Factors to same Factor Value

Dear All,
Probably something very easy, but I am looking for the most efficient ways to achieve this.
Consider the following snippet

y<-c('a','b','c','d','e','f','g')
x<-rnorm(length(y))
df<-data.frame(y,x)

leading to

> df$y
[1] a b c d e f g
Levels: a b c d e f g

Now, I would like to replace levels ('e','f','g') of df$y with a new level 'other' so that levels(df$y) returns

a b c d other

What is the easiest way to achieve this, considering that

df$y[5:7]<-'other'
Does not work?
Cheers

Lorenzo

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list