stata
stata

Reputation: 533

How to replace values in a Vector

data1<-data.frame(x1=c("a","b"),x2=c("b","b"),x3=c("c","b"),x4=c("d","b"),stringsAsFactors=FALSE)
aaa<-as.character(data1[1,])
aaa

I want to replace a with \M, b with \N, others with \O in aaa vector. How to do it? Thank you!

Upvotes: 0

Views: 122

Answers (3)

Tyler Rinker
Tyler Rinker

Reputation: 110054

Another overkill approach:

library(qdapTools)
lookup(aaa, list(`\\M`="a", `\\N` ="b"), missing = "\\O")

## [1] "\\M" "\\N" "\\O" "\\O"

Upvotes: 1

thelatemail
thelatemail

Reputation: 93938

Use a lookup vector to automate this:

vec <- setNames(c("\\M","\\N"),c("a","b"))
ifelse(aaa %in% names(vec),vec[as.character(aaa)],"\\O")

#[1] "\\M" "\\N" "\\O" "\\O"

Upvotes: 1

Federico Giorgi
Federico Giorgi

Reputation: 10765

Easy answer would be:

aaa[aaa!="a"&aaa!="b"]<-"\\O"
aaa[aaa=="a"]<-"\\M"
aaa[aaa=="b"]<-"\\N"

But your problem here seems that you are trying to define unrecognized symbols such as \M.

Upvotes: 1

Related Questions