Recently I have a problme to convert my dataframe. Now I have a data which some columns is the first letter of their name coded as number. For example, Anna coded as 1 due to her first letter of name is "A". Now, I want to change this number to letter in R. Is there any pacakge or tools to help me finshed that? Thanks everyone!
I have try to write a function,but it's so inefficient. I have also tried strsplit function, but it can't use in dataframe.
CodePudding user response:
Welcome to StackOverflow! Here is one simple way:
> which("R" == LETTERS) - which("A" == LETTERS)
[1] 17
>
It takes advantage of
- R having vectors
LETTERS
andletters
- boolean matching to the letter you look for
which
providing an index- which we can compute a difference on
(And please do not post links to screenshots or even screenshots. Text is best.)
CodePudding user response:
If you want to change numbers into their correspnding letters in the (English) alphabet:
nmb <- c(1,3,5,2,12,4,20)
LETTERS[nmb]
[1] "A" "C" "E" "B" "L" "D" "T"
LETTERS is a built-in constant in R. If you subset it based on the numbers you want to convert, you will get the corresponding letters.