dataframe - Fast way to "translate" a column of variables in R using a lookup table -


this question has answer here:

starting use r in data analysis, still relative newbie. have data frame looks this:

locations

loc idnum 100000001 1 100000009 7 100000021 3 100000004 2 100000017 3 100000007 7 100000067 5 

and matrix list of id numbers (from second column) , corresponding strings (like translation table of sorts).

looks similar this:

names

idnum   idnames 1  nnw43 2  n3 3  se21 4  sw54 5  w6 6  w12 7  ne10 ... 

so matrix shorter because each id number has corresponding string, in original data frame there more 1 loc contain same idnum.

i'm sure there easy way match each id number string , create new data frame first column same second containing strings instead of id numbers, i'm not sure is. know i'm told if use loops in r you're doing wrong.

result

loc name 100000001 nnw43 100000009 ne10 100000021 se21 100000004 n3 100000017 se21 100000007 ne10 100000067 w6 

i had hard time figuring out how title question input on useful well. in advance!

edited provide reproducible example

if names matrix or dataframe has sequentially numbered names, use idnum index object's idnames vector:

 locations$name <- names$idnames[locations$idnum] 

if not sequentially numbered, need use match proper row number:

 locations$name <- names$idnames[match( locations$idnum, names$idnum) ] 

(this in probability duplicate question , answer.)


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -