Search code examples
rlikert

R: How to apply a command on selected variables in a data frame?


I need to use rescale some of ma variables from a 5 point to a 7 point likert scale. Therefore I want to use package surveytoolbox with command likert_convert. Also I want to create a vector i that names the variables names the command should be used on.

The command itself would work like surveytoolbox::likert_convert(surveydata$q1, 5,1,7,1) to rescale the variable from a 5 point to a 7 point likert scale.

However, I cannot manage to apply that command on multiple variables on the data frame at the same time and would appreciate if anyone could help me.

Thanks a lot for your help!

You can find a reproducible sample here:

#create data
surveydata <- as.data.frame(replicate(6,sample(0:1,1000,rep=TRUE)))

# change values of columns
surveydata$V3 <- sample(5, size = nrow(surveydata), replace = TRUE)
surveydata$V4 <- sample(5, size = nrow(surveydata), replace = TRUE)
surveydata$V5 <- sample(5, size = nrow(surveydata), replace = TRUE)
surveydata$V6 <- sample(5, size = nrow(surveydata), replace = TRUE)

#create group column
surveydata$group <- c(1,2)

# rename columns
colnames(surveydata)[1] <- "gender"
colnames(surveydata)[2] <- "expert"
colnames(surveydata)[3] <- "q1"
colnames(surveydata)[4] <- "q2"
colnames(surveydata)[5] <- "q3"
colnames(surveydata)[6] <- "q4"

#create vector
i <- c("q1", "q2","q3","q4")

Solution

  • Here's an approach with dplyr:

    #remotes::install_github("martinctc/surveytoolbox")
    library(surveytoolbox)
    library(dplyr)
    surveydata %>%
      mutate_at(vars(starts_with("q")), likert_convert,
                top.x = 5, bot.x = 1, top.y = 7, bot.y = 1)
    #    gender expert  q1  q2  q3  q4 group
    #1        0      0 7.0 2.5 2.5 1.0     1
    #2        1      0 2.5 7.0 5.5 7.0     2
    #3        1      1 5.5 1.0 7.0 4.0     1
    #4        1      0 7.0 5.5 2.5 7.0     2
    

    If you prefer a base R approach, you can use apply:

    surveydata[,3:6] <- apply(surveydata[,3:6], 2, likert_convert,
                top.x = 5, bot.x = 1, top.y = 7, bot.y = 1)
    surveydata
    #    gender expert  q1  q2  q3  q4 group
    #1        0      0 7.0 2.5 2.5 1.0     1
    #2        1      0 2.5 7.0 5.5 7.0     2
    #3        1      1 5.5 1.0 7.0 4.0     1
    #4        1      0 7.0 5.5 2.5 7.0     2