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

  • 本文关键字:变量 应用 命令 数据 r likert
  • 更新时间 :
  • 英文 :


我需要使用将一些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")

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

我不熟悉likert_convert函数,所以我用以下函数替换它:

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

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

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

最新更新