rodrigarco
rodrigarco

Reputation: 123

Replacing numbers to letters in dataframe in r

So basically I have a column in a data frame like:

df <- data.frame(well = c("0","1",NA,"1","1","2","2","3","4","3"))

I just want to create a new column by replacing "0" to "A", "1" to "B",...,"7" to "H". I was trying this unsuccessfully:

lxn <-  data.frame(old_name = c(0,1,2,3,4,5,6,7), 
               new_name = c("A","B","C","D","E","F","G","H"))
map <- lxn$new_name
names(map) <- lxn$old_name
df <- df %>% mutate(well_l = ifelse(well %in% names(map), 
                     map[well], 
                     well)) 

If you try it you can see that the output is basically the well number + 1. I do not know why I am not retrieving the letters (new_name) and getting the number of well + 1.

Hope someone can help me.

Upvotes: 1

Views: 1030

Answers (2)

r.user.05apr
r.user.05apr

Reputation: 5456

No loop required:

df <- data.frame(well = c("0","1",NA,"1","1","2","2","3","4","3"))

lxn <-  data.frame(old_name = c(0,1,2,3,4,5,6,7), 
                   new_name = c("A","B","C","D","E","F","G","H"))

df %>%
  mutate(well = set_names(lxn$new_name, lxn$old_name)[well])

# well
# 1     A
# 2     B
# 3  <NA>
#   4     B
# 5     B
# 6     C
# 7     C
# 8     D
# 9     E
# 10    D

Upvotes: 3

jay.sf
jay.sf

Reputation: 72683

You could use the built-in constant LETTERS.

df <- transform(df, let=LETTERS[well])
df
#    well  let
# 1     0    A
# 2     1    B
# 3  <NA> <NA>
# 4     1    B
# 5     1    B
# 6     2    C
# 7     2    C
# 8     3    D
# 9     4    E
# 10    3    D

Upvotes: 4

Related Questions