Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert alphabetic letters to their relative position in the alphabet (R)

Tags:

r

I would like to get the relative position in the alphabet of each letter in a string. To demonstrate something not working properly:

which(letters %in% unlist(strsplit("acba", split="")))

result:

#[1] 1 2 3

I'm looking for a code snippet returning:

#[1] 1 3 2 1

Suggestions?

like image 559
hbelbo Avatar asked Oct 20 '25 14:10

hbelbo


1 Answers

If we need to replace the string elements with numbers, chartr can be used

chartr('abc', '123', 'acba')
#[1] "1321"

Or after doing the strsplit/unlist, we can match with the letters to get the numeric index.

match(unlist(strsplit("acba", split="")), letters)
#[1] 1 3 2 1

In the OP's code, when we use %in% it gives a logical output i.e.

letters %in% unlist(strsplit("acba", split=""))
#[1]  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

As we can understand from the output, only the first 3 elements in the letters match with the unlist output. So wrapping with which will give only the numeric index of that sequence i.e. 1, 2, 3. But, if we use the reverse i.e.

 unlist(strsplit("acba", split="")) %in% letters
 #[1] TRUE TRUE TRUE TRUE

and then wrap with which, it will show 1, 2, 3, 4.

like image 177
akrun Avatar answered Oct 22 '25 02:10

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!