Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
724 views
in Technique[技术] by (71.8m points)

r - replace multiple values in a column for a single one

I have a rather basic question. I have several values in a column that I would like to replace for a single one, for instance:

a<-data.frame(T=LETTERS[5:20],V=rnorm(16,10,1))

and I would like to change all "E", "S", "T" in T for "AB", so I tried

a[a$T==c("E","S","T")]<-"AB"

and it gives me several warnings, and ends up replacing all to "AB"

I think it has something to do with levels and level's labels but I was not able to replace only some of the values, I would have to re-label each. Sorry for the trouble, and thanks for any help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use function recode() from library car to change values also for the factors.

library(car)
a$T<-recode(a$T,"c('E','S','T')='AB'")

If you need to replace different values with different other values then all statements can be written in one function call.

recode(a$T,"c('E','S','T')='AB';c('F','G','H')='CD'")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...