Reputation: 356
I have this problem which I can solve manually but I feel there must be an easier answer. I want to replace 2 with A, 22 with B, 4 with C, ... I have all the values I want to replace in an array and another [A,B,C,D,...]. Is there an easy way to perform this replacement? Thanks, Miguel
Upvotes: 1
Views: 1187
Reputation: 3710
You can use named vectors.
x <- sample(1:10, 8)
x
# [1] 4 9 6 10 8 3 7 5
y <- c("A", "B", "C")
names(y) <- 1:3
x[x%in%names(y)] <- y[x[x%in%names(y)]]
x
# [1] "4" "9" "6" "10" "8" "C" "7" "5"
Upvotes: 4
Reputation: 2368
Use data.table
DT[column1 == "2", column1 := "A"]
If you want to do a group of them at a time, then use setkey
from data.table
and merge
the dataset with the reference dataset.
setkeyv(DT, 'column1')
setkeyv(referenceSet, 'oldVars')
merge(DT, referenceSet, all.x = TRUE)
Upvotes: 2