Reputation: 533
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
Reputation: 110054
Another overkill approach:
library(qdapTools)
lookup(aaa, list(`\\M`="a", `\\N` ="b"), missing = "\\O")
## [1] "\\M" "\\N" "\\O" "\\O"
Upvotes: 1
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
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