for loop - R - "find and replace" integers in a column with character labels -



for loop - R - "find and replace" integers in a column with character labels -

i have 2 info frames first (df1) similar this:

ba ram sheep 30 1 33.2 120.9 27 3 22.1 121.2 22 4 39.1 99.1 11 1 20.0 101.6 9 3 9.8 784.3

the sec (df2) contains titles column "ram":

v1 v2 1 reddish 2 grn 3 ylw 4 blu

i need replace df1$ram corresponding character strings of df2$v2:

ba ram sheep 30 reddish 33.2 120.9 27 ylw 22.1 121.2 22 blu 39.1 99.1 11 reddish 20.0 101.6 9 ylw 9.8 784.3

i can nested loop, feels inefficient:

x <- c(1:nrows(df1)) y <- c(1:4) (i in x) { (j in y) { if (df1$ram[i] == x) { df1$ram[i] <- df2$v2[y] } } }

is there way more efficiently??!?! know there is. i'm noob.

use merge

> result <- merge(df1, df2, by.x="ram", by.y="v1")[,-1] # merging data.frames > colnames(result)[4] <- "ram" # setting name

the next getting output in order showed us

> result[order(result$ba, decreasing = true), c("ba", "ram", "you", "sheep")] ba ram sheep 1 30 reddish 33.2 120.9 3 27 ylw 22.1 121.2 5 22 blu 39.1 99.1 2 11 reddish 20.0 101.6 4 9 ylw 9.8 784.3

r for-loop apply

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -