How to convert original input to index value in R

Thanks for the help. I have an original input file " foo.txt

" and another dictionary

file " dic.csv

" where each line in the dic file is a pair key-value

, the key is one character and the value is another character.

maybe foo.txt :

abcd
dcba
aaaa

      

and dic.csv :

a 1
b 2
c 3
d 4

      

I want to convert "foo.txt" to values ​​in the dic file according to the matching key, for example as a result:

1234
4321
1111

      

Is there an efficient way to do this?

Thank!

+3


source to share


2 answers


Try

chartr(paste(d1$Col1, collapse=''), paste(d1$Col2, collapse=""), v1)
#[1] "1234" "4321" "1111"

      

Or instead of two paste

, we can loop through withsapply

v2 <- sapply(d1, paste, collapse='')
chartr(v2[1], v2[2], v1)
#[1] "1234" "4321" "1111"

      

Or using mgsub

fromqdap



library(qdap)
mgsub(d1$Col1, d1$Col2, v1)
#[1] "1234" "4321" "1111"

      

or

library(gsubfn)
gsubfn('[abcd]', list(a=1, b=2, c=3, d=4), v1)
#[1] "1234" "4321" "1111"

      

data

 v1 <- c('abcd', 'dcba', 'aaaa')
 d1 <- data.frame(Col1= letters[1:4], Col2=1:4, stringsAsFactors=FALSE)

      

+4


source


You can turn the dictionary data.frame

into a named vector and then use indexing:



foo <- c("abcd", "dcba", "aaaa")
dict <- data.frame(key = letters[1:4], value = 1:4)
dict.vec <- setNames(dict$value, dict$key)

sapply(foo, function(x) 
    paste(dict.vec[strsplit(x, "")[[1]]], collapse = ""))
#   abcd   dcba   aaaa 
# "1234" "4321" "1111"  

      

+2


source







All Articles