0

I want to find a more elegant way to transform my data from likert scale to a standardized scale. Plyr's mapvalues seems to work but it isn't elegant. I tried purrr but it didn't work as I'd hoped.

   data$var1 <- mapvalues(data$var1, 
      from=c("1","2","3", "4", "5"), 
      to=as.integer(c("0", "25", "50", "75", "100"))

I have several variables that I would like to transform so any insights on doing this using purrr functions would be great.

This is my first stackoverflow post so forgive me if I am not following the right protocol.

-RP

RP4377
  • 3
  • 1
  • Please make a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Martin Gal Aug 30 '21 at 21:56

2 Answers2

1

Since there is a clear pattern in replacement here we can subtract 1 from var1 and multiply by 25. Instead of replacing var1 I have created a new column var2 for easier understanding.

library(dplyr)

data <- data %>% mutate(var2 = 25 * (var1 - 1))
data

#   var1 var2
#1     3   50
#2     3   50
#3     2   25
#4     2   25
#5     3   50
#6     5  100
#7     4   75
#8     1    0
#9     2   25
#10    3   50

If there is no such clear pattern and since plyr has been retired you may use dplyr::recode

data <- data %>% 
        mutate(var2 = recode(var1, `1`=0, `2`=25, `3`=50, `4`=75, `5`=100))

data

It is easier to help if you provide data in a reproducible format -

set.seed(123)
data <- data.frame(var1 = sample(5, 10, replace = TRUE))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

If you're looking for a more concise solution, you could recode your variable using dplyr's mutate, rather than a purrr function:

sampledata %>%
  mutate(var1 = seq(from=0, to=100, by=25)[var1])

To apply this across multiple columns, use across inside mutate, selecting the columns you'd like to transform, e.g.:

sampledata %>%
  mutate(across(.cols = everything(), ~ seq(from=0, to=100, by=25)[.]))
Rory S
  • 1,278
  • 5
  • 17