R:如何对数据框中的选定变量应用命令?

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

我需要将一些 ma 变量从 5 点重新调整为 7 点李克特量表。因此,我想将包 surveytoolbox 与命令 likert_convert 一起使用。我还想创建一个向量 i 来命名应该使用命令的变量名称。

命令本身的工作方式类似于 surveytoolbox::likert_convert(surveydata$q1, 5,1,7,1) 将变量从 5 点重新调整为 7 点李克特量表。

但是,我无法同时将该命令应用于数据框上的多个变量,如果有人能帮助我,我将不胜感激。

非常感谢您的帮助!

您可以在此处找到可重现的样本:

#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")

我不熟悉 likert_convert 函数所以我将其替换为以下函数:

do.sth <- function(x) return(10 + x)

这可以很容易地应用于 surveydata 中在 i 中命名的行中的任何值,如下所示:

surveydata[, i] <- apply(surveydata[, i], 1:2, do.sth)

这是 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

如果您更喜欢基本的 R 方法,可以使用 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