Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a column through a dictionary in R

Tags:

list

dataframe

r

I have a data frame in R. One column of this data frame takes values from 1 to 6. I have another data frame that maps this column. There is some way to substitute the values in this column without using loops (using some function)?

     [,1] [,2]   
[1,] "1"  "A"
[2,] "2"  "B"
[3,] "3"  "C"
[4,] "4"  "D"

[1] 4 2 2 3 4 1 4 4

Exists a function that return the vector below without using loops?

[1] D B B C D A D D
like image 560
Rofellos Avatar asked Feb 26 '15 20:02

Rofellos


1 Answers

You can try

v1 <- c(4, 2, 2, 3, 4, 1, 4, 4)
LETTERS[v1]
#[1] "D" "B" "B" "C" "D" "A" "D" "D"

Suppose if your mapping dataset 2nd column is not just "LETTERS"

d1 <- data.frame(Col1=c(1,3,4,2), Col2=c('j1', 'c9', '19f', 'd18'),
                     stringsAsFactors=FALSE)

unname(setNames(d1[,2], d1[,1])[as.character(v1)])
#[1] "19f" "d18" "d18" "c9"  "19f" "j1"  "19f" "19f"

Or

d1$Col2[match(v1, d1$Col1)]
#[1] "19f" "d18" "d18" "c9"  "19f" "j1"  "19f" "19f"
like image 197
akrun Avatar answered Oct 14 '22 21:10

akrun