The voices to the question will greatly puzzle me ... so do you need an answer to this question?
Using the loop-based method, as the OP intended, is:
Y <- numeric(length(X)) ## initialize a numeric vector `Y`, of the same length of `X` ## loop through all elements of `X`, use `if-else` to allocate value for `Y` for (i in seq_along(X)) { if (X[i] == "A") Y[i] <- 1 else if (X[i] == "B") Y[i] <- 2 else if (X[i] == "C") Y[i] <- 3 }
Fully vectorial method,
Y <- match(X, LETTERS[1:3])
Here, LETTERS are internal R-constants for capital letters. There are several constants in R, and you can get them all by reading the ?Constants documentation.
source share