convert numbers to letters in a data.frame

3.7k views Asked by At

In R, I have some matrices of numbers and I am going to convert each number to its equivalent letter; 1 to "a", 2 to "b", and so on.

Assume this is the matrix:

set.seed(1)
x <- data.frame(matrix(sample(1:16,12,T),nrow=3,ncol=4))
#  X1 X2 X3 X4
#1  5 15 16  1
#2  6  4 11  4
#3 10 15 11  3

This is the expected output:

#  X1 X2 X3 X4
#1  e  o  p  a
#2  f  d  k  d
#3  j  o  k  c

I used letters[x] and letters[list(x)] but it gave this

Error in letters[list(x)] : invalid subscript type 'list'

3

There are 3 answers

0
kath On BEST ANSWER

Using sapply is also possible:

sapply(x, function(i) letters[i])
#      X1  X2  X3  X4 
# [1,] "e" "o" "p" "a"
# [2,] "f" "d" "k" "d"
# [3,] "j" "o" "k" "c"
0
G. Grothendieck On

First convert the data frame to a plain vector and then it can be used to subscript letters. Then replace the contents of x with that vector. By using replace we can avoid overwriting the original x.

replace(x, TRUE, letters[unlist(x)])

giving:

  X1 X2 X3 X4
1  e  o  p  a
2  f  d  k  d
3  j  o  k  c
0
akrun On

After converting the 'x' to matrix, use that as index for the built-in letters and assign it to the original dataset

x[] <- letters[as.matrix(x)]
x
#   X1 X2 X3 X4
#1  e  o  p  a
#2  f  d  k  d
#3  j  o  k  c

Or this can be done with tidyverse

library(dplyr)
x %>%
   mutate_all(funs(letters[.]))