Reputation: 1273
I have a variable which is coded with both letters and numbers and I am trying to get it all into numbers. The letters are A through Z, and I would like them coded as 1 through 26. The numeric entries are 2 through 8, and I would like them coded as 27 through 33. I can't seem to find a good way of doing this.
For example, my variable looks similar to:
var = c('A',2,3,8,'C','W',6,'T')
I would want A = 1, 2 = 27, 3 = 28, 8 = 33, C = 3, W = 23, 6 = 31, and T = 20.
Basically var is A:Z and 2:8. But the numbers [2:8] need to be larger numbers than the letters. The letters need to correspond to their position in the alphabet.
Upvotes: 1
Views: 457
Reputation: 3310
match(var, c(LETTERS, 2:8))
also looks like it gives the answer you're looking for.
Upvotes: 2
Reputation: 887088
We could do this using
library(dplyr)
v1 <- setNames(as.character(27:33), 2:8)[var]
v2 <- setNames(as.character(1:26), LETTERS)[var]
as.vector(coalesce(v1, v2))
Upvotes: 1