Fra
Fra

Reputation: 23

Create a new variable renaming its elements after the elements of an existing variable in R

I would like to create a new variable which elements are named after the elements of an existing variable, but with str_replace_all, it works only for the first cases... Thank you

df<-data.frame(A=c("HotWater", "ColdWater", "HotRock", "ColdRock", "ColdRock","ColdRock"))
df$A<-as.factor(df$A)
old<-c("HotWater", "ColdWater", "HotRock", "ColdRock")

#HotWater= hot fluid, ColdWater=cold fluid , HotRock= hot solid, ColdRock = cold solid

#I need only HF for Hot Fluid, CF for Cold Fluid and so on...

new<-c("HF", "CF", "HS", "CS")

#I try to create a new variable with the correct labels

df$B<-str_replace_all(df$A,old, new)



#however I get this:

          A        B
1  HotWater       HF
2 ColdWater       CF
3   HotRock       HS
4  ColdRock       CS
5  ColdRock ColdRock
6  ColdRock ColdRock

#but I need this:
          A        B
1  HotWater       HF
2 ColdWater       CF
3   HotRock       HS
4  ColdRock       CS
5  ColdRock       CS
6  ColdRock       CR

Upvotes: 2

Views: 57

Answers (1)

Taufi
Taufi

Reputation: 1577

Try the following.

Code:

df$b <- mgsub::mgsub(as.character(df$A), 
             c("HotWater", "ColdWater", "HotRock", "ColdRock"), 
             c("HF", "CF", "HS", "CS"))

Output:

> df
          A  B
1  HotWater HF
2 ColdWater CF
3   HotRock HS
4  ColdRock CS
5  ColdRock CS
6  ColdRock CS

Upvotes: 1

Related Questions