Gboyega.A
Gboyega.A

Reputation: 25

How do i replace multiple occurences of multiple values in a vector

I have a column within a data.frame with multiple occurrences of each of its unique values which i need to replace with different values. How can I achieve this?

I created a factor of the unique values and tried replacing each element by looping over the factor levels using the gsub function

nf <- factor(1, 2, 3, 4, 5, 6)
let <- c("a", "b", "c", "d", "e", "f")

dat <- c(1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6)

dat <- for (i in levels(nf)){
gsub(i,let[i], dat
}

I expected an output of :

"a" "b" "b" "c" "c" "c" "d" "d" "d" "d" "e" "e" "e" "e" "e" "f" "f" "f" "f" "f" "f" 

but instead I get: NULL.

Upvotes: 1

Views: 80

Answers (1)

Maurits Evers
Maurits Evers

Reputation: 50738

Are you just after

let[dat]
#[1] "a" "b" "b" "c" "c" "c" "d" "d" "d" "d" "e" "e" "e" "e" "e" "f" "f" "f" "f"
#[20] "f" "f"

Or if you prefer a factor

factor(dat, labels = let)

Upvotes: 2

Related Questions