How can I convert a list of character strings to unique single characters?

Viewed 119

I have a variable which is a list of different bird calls in sequence. I would like to give each different call a unique, single character. I have found a way to give them unique numbers, but once I reach 10 that is no good as I would need to then turn this list into a string of letters and/or numbers.

For example, some of my dataframe looks like this:

> d1
  Order        Type
1     1 Bowerbird a
2     2     Catbird
3     3       Robin
4     4   Scrubwren
5     5 Bowerbird b
6     6  Kookaburra
7     7     Catbird
8     8     Rosella

I would like to convert each unique call into a different character. It can be lower case letters, upper case letters, or numbers, as long as they are all single digits. For example:

> d1
  Order        Type Unique
1     1 Bowerbird a      a
2     2     Catbird      b
3     3       Robin      c
4     4   Scrubwren      1
5     5 Bowerbird b      2
6     6  Kookaburra      A
7     7     Catbird      b
8     8     Rosella      B

This sequence of calls could then be written as "abc12AbB".

I have about 40 different possible calls so I don't want to do this using the ifelse function if I can avoid it. Is there a way to convert each character string to a unique character?

1 Answers

We can use upper and lower case alphabets with numbers 0-9 which comes out to be of size 62.

set.seed(123)
df$unique <- sample(c(letters, LETTERS, 0:9))[factor(df$Type)]

df
#  Order       Type unique
#1     1 Bowerbirda      E
#2     2    Catbird      Y
#3     3      Robin      c
#4     4  Scrubwren      X
#5     5 Bowerbirdb      o
#6     6 Kookaburra      n
#7     7    Catbird      Y
#8     8    Rosella      P

You don't really need sample here but adding it to introduce randomness.

You can write sequence of calls as

paste0(df$unique, collapse = "")
#[1] "EYcXonYP"
Related