[R] a question about replacing a column that is factor

Berend Hasselman bhh at xs4all.nl
Sat Jul 25 17:20:57 CEST 2009



jlfmssm wrote:
> 
> Sorry, I didn't get it.
> I made a simple example to explain what I want
> 
>> x=c(1,2,4,4)
>> y=c("A",1,2,"A")
>> test<-as.data.frame(cbind(x,y))
>> test
>   x y
> 1 1 A
> 2 2 1
> 3 4 2
> 4 4 A
>> test[test$x==4,]$y<-'B'
> Warning message:
> In `[<-.factor`(`*tmp*`, iseq, value = c("B", "B")) :
>   invalid factor level, NAs generated
>> test
>   x    y
> 1 1    A
> 2 2    1
> 3 4 <NA>
> 4 4 <NA>
> 
> actually, what I want is
> 
>> test
>   x    y
> 1 1    A
> 2 2    1
> 3 4    B
> 4 4    B
> 

Try this

x=c(1,2,4,4)
y=c("A",1,2,"A")
atest <- data.frame(x=x,y=y)
str(atest)
atest
levels(atest$y)[4] <- 'B'
atest[atest$x==4,]$y <- 'B'
str(atest)
atest

This gives the following output

> x=c(1,2,4,4)
> y=c("A",1,2,"A")
> atest <- data.frame(x=x,y=y)
> str(atest)
'data.frame':	4 obs. of  2 variables:
 $ x: num  1 2 4 4
 $ y: Factor w/ 3 levels "1","2","A": 3 1 2 3
> atest
  x y
1 1 A
2 2 1
3 4 2
4 4 A
> levels(atest$y)[4] <- 'B'
> atest[atest$x==4,]$y <- 'B'
> str(atest)
'data.frame':	4 obs. of  2 variables:
 $ x: num  1 2 4 4
 $ y: Factor w/ 4 levels "1","2","A","B": 3 1 4 4
> atest
  x y
1 1 A
2 2 1
3 4 B
4 4 B


Berend
-- 
View this message in context: http://www.nabble.com/a-question-about-replacing-a-column-that-is-factor-tp24654365p24658796.html
Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list