Debojit Roy
Debojit Roy

Reputation: 35

Replacing string vector entries with some predetermined numerical values in R

Suppose I have two vectors of the form vec1 = c("AAA","AA+","","D") and vec2 = c("AAA","","D","AA+"). I want to replace "AAA" = 1, "AA+" = 2, "D" = 3, and finally blanks with zeros

Thus I want to create two more vectors based upon vec1 and vec2 which I will be referring to for my further analysis. The transformed form of Vec1 should be in form like - v1 = (1,2,0,3) and for vec2 it should be as -v2 =(1,0,3,2)

Upvotes: 1

Views: 73

Answers (2)

akrun
akrun

Reputation: 887421

We may use vectorized option with a named vector

vec1new <- setNames(c(1, 2, 3), c("AAA", 'AA+', 'D'))[vec1]
vec1new[is.na(vec1new)] <- 0

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71600

Use mapply and match:

> as.vector(mapply(function(x) match(x, c("", "AAA", "AA+", "D")) - 1, vec1))
[1] 1 2 0 3

Or if you're fine with it not being a vector:

> mapply(function(x) match(x, c("", "AAA", "AA+", "D")) - 1, vec1)
AAA AA+       D 
  1   2   0   3 
> 

Upvotes: 1

Related Questions