user1817709
user1817709

Reputation: 93

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!

Upvotes: 1

Views: 17465

Answers (4)

Alan G&#243;mez
Alan G&#243;mez

Reputation: 378

An R Base solution is:

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

Upvotes: 0

flodel
flodel

Reputation: 89097

This would maintain your data structure (a factor like you guessed):

x <- levels(a$T)
levels(a$T) <- ifelse(x %in%  c("E","S","T"), "AB", x)

or

levels(a$T)[levels(a$T) %in%  c("E","S","T")] <- "AB"

Edit: if you have many such replacements, it is a little more complicated but not impossible:

from <- list(c("E","S","T"), c("J", "K", "L"))
to   <- c("AB", "YZ")

find.in.list <- function(x, y) match(TRUE, sapply(y, `%in%`, x = x))
idx.in.list  <- sapply(levels(a$T), find.in.list, from)
levels(a$T)  <- ifelse(is.na(idx.in.list), levels(a$T), to[idx.in.list])

a$T
#  [1] AB F  G  H  I  YZ YZ YZ M  N  O  P  Q  R  AB AB
# Levels: AB F G H I YZ M N O P Q R

Upvotes: 4

statquant
statquant

Reputation: 14400

Do you really want factors there ??? If not (I think you do not) do options(stringsAsFactors=FALSE) So it is much simpler than that... => a[a$T %in% c("E","S","T"),"T"]<-"AB"

Upvotes: 1

Didzis Elferts
Didzis Elferts

Reputation: 98579

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'")

Upvotes: 7

Related Questions