Search code examples
rfunctiondata-conversionsurvey

Changing vector of 1-10 to vector of 1-3 using R


I am using R to analyze a survey. Several of the columns include numbers 1-10, depending on how survey respondents answered the respective questions. I'd like to change the 1-10 scale to a 1-3 scale. Is there a simple way to do this? I was writing a complicated set of for loops and if statements, but I feel like there must be a better way in R.

I'd like to change numbers 1-3 to 1; numbers 4 and 8 to 2; numbers 5-7 to 3, and numbers 9 and 10 to NA.

So in the snippet below, OriginalColumn would become NewColumn.

OriginalColumn=c(4,9,1,10,8,3,2,7,5,6)
NewColumn=c(2,NA,1,NA,2,1,1,3,3,3)

Is there an easy way to do this without a bunch of crazy for loops? Thanks!


Solution

  • You can do this using positional indexing:

    > c(1,1,1,2,3,3,3,2,NA,NA)[OriginalColumn]
     [1]  2 NA  1 NA  2  1  1  3  3  3
    

    It is better than repeated/nested ifelse because it is vectorized (thus easier to read, write, and understand; and probably faster). In essence, you're creating a new vector that contains that new values for every value you want to replace. So, for values 1:3 you want 1, thus the first three elements of the vector are 1, and so forth. You then use your original vector to extract the new values based on the positions of the original values.