r - Replacing values in column X with values from column Y, but only if the values of X match the values in column Z -


i have 2 data frames, 1 one column (x), , other 2 columns (y & z):

column x contains numbers 1:99, has letters instead of numbers, ie: 1, 2, 3, a, 5, b, 7, 8, c, d, 11, 12 etc.

column y contains these same letters, paired (as appearing in column z) numbers, ie:

a 4

b 6

c 9

d 10

how can replace letters in column x values of column z, according whether letters in column x match letters in column y? result in column x being 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 etc.

a straightforward merge won't work (i need retain values in x) , i'm not sure how can use sub conditionally. also, column y , z contain more rows needed column x, can't use cbind. i'm not skilled @ using regex, although best bet...

any appreciated!

i'd use loop. creating data:

df1 <- data.frame(x = c("a", 5, "b", 7, 8, "c", "d", 11, 12)) df2 <- data.frame(y = c("a", "b", "c", "d"),                   z = c(4, 6, 9, 10)) 

we need make sure things character vectors, not factors, testing equality

df1$x <- as.character(df1$x) df2$y <- as.character(df2$y) 

then can replacing:

for (i in 1:nrow(df2)) {     df1$x[df1$x == df2$y[i]] <- as.character(df2$z[i]) } 

finally, i'm guessing want x numeric letters gone:

df1$x <- as.numeric(df1$x) 

Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -