[R] replace elements of a data frame

Arnaud Gaboury arnaud.gaboury at a2ct2.com
Wed Feb 8 11:10:53 CET 2012


> names1<-recode(df$names,"'BO'='BOO';'CL'='CLR';'C'='CC'")
> df1<-data.frame(names1,price)
> df1
  names1 price
1    BOO    10
2     CC    25
3    CLR    20

TY for the tip.

Any possibility to write this in one single line?

Arnaud Gaboury
 
A2CT2 Ltd.

-----Original Message-----
From: Berend Hasselman [mailto:bhh at xs4all.nl] 
Sent: mardi 7 février 2012 20:46
To: Arnaud Gaboury
Cc: Jorge I Velez; r-help at r-project.org
Subject: Re: [R] replace elements of a data frame


On 07-02-2012, at 20:24, Arnaud Gaboury wrote:

> I did indeed have a look at recode(), and was able to replace, but an error warning :
> 
>> recode(names,"BO","BOO",df)
> Warning message:
> In recode.default(names, "BO", "BOO", df) :
>  Name(s) of vars duplicates with an object outside the dataFrame.
> 
>> df
>  names price
> 1   BOO    10
> 2     C    25
> 3    CL    20
> 
> As you can see, "BO" has been replaced by "BOO", but with a warning!

library(car)

 names<-c("BO","C","CL")
price<-c("10","25","20")
df<-data.frame(names,price)
recode(df$names,"'BO'='BOO'; 'CL'='CLO'; 'C'='CR'")

results in

[1] BOO CR  CLO
Levels: BOO CLO CR

Note the single quotes.

Berend



More information about the R-help mailing list