Search code examples
rstringreplacenumbersletters

convert numbers to letters in a data.frame


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'


Solution

  • 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"