反向评分项目

Nic*_*ost 6 reverse scoring r

我对大约80个项目进行了调查,主要是项目是平衡的(更高的分数表示更好的结果),但其中大约20个是负面的平衡,我需要找到一种方法来反转在R中负面平衡的那些.我是完全失去了如何这样做.我绝对是一个R初学者,这可能是一个愚蠢的问题,但是有人能指出我的代码方向吗?

小智 8

只需使用 tidyverse 转换 @eipi10 的答案:

# Create same fake data: Three questions answered on a 1 to 5 scale
set.seed(1)
dat <- data.frame(Q1 = sample(1:5,10, replace=TRUE), 
                  Q2 = sample(1:5,10, replace=TRUE),
                  Q3 = sample(1:5,10, replace=TRUE))

# Reverse scores in the desired columns (Q2 and Q3)

dat <- dat %>% 
  mutate(Q2Reversed = 6 - Q2,
         Q3Reversed = 6 - Q3)
Run Code Online (Sandbox Code Playgroud)


eip*_*i10 7

以下是一些可以适应您的数据的假数据示例:

# Fake data: Three questions answered on a 1 to 5 scale
set.seed(1)
dat = data.frame(Q1=sample(1:5,10,replace=TRUE), 
                 Q2=sample(1:5,10,replace=TRUE),
                 Q3=sample(1:5,10,replace=TRUE))

dat
   Q1 Q2 Q3
1   2  2  5
2   2  1  2
3   3  4  4
4   5  2  1
5   2  4  2
6   5  3  2
7   5  4  1
8   4  5  2
9   4  2  5
10  1  4  2

# Say you want to reverse questions Q1 and Q3
cols = c("Q1", "Q3")

# Reverse scores in the desired columns 
dat[,cols] = lapply(cols,  function(x) 6 - dat[, x])

# Per @akrun's comment, I was making it more complicated than necessary. 
# You can just do this instead of the `lapply` thing above:
dat[ ,cols] = 6 - dat[ ,cols]

dat
   Q1 Q2 Q3
1   4  2  1
2   4  1  4
3   3  4  2
4   1  2  5
5   4  4  4
6   1  3  4
7   1  4  5
8   2  5  4
9   2  2  1
10  5  4  4
Run Code Online (Sandbox Code Playgroud)

  • 用 'max(dat[, cols]) + 1' 替换 6 将代码扩展到其他情况并防止为一个函数调用加载库 (3认同)
  • 对于将来发现此问题的任何人,`psych` 包有一个名为 `reverse.code()` 的函数可以执行此操作。 (2认同)

Jef*_*ker 7

这是使用 psych 包的另一种方法。如果您正在处理调查数据,这个包有很多很好的功能。基于@eipi10 数据:

# Fake data: Three questions answered on a 1 to 5 scale
set.seed(1)
original_data = data.frame(Q1=sample(1:5,10,replace=TRUE), 
                 Q2=sample(1:5,10,replace=TRUE),
                 Q3=sample(1:5,10,replace=TRUE))
original_data

# Say you want to reverse questions Q1 and Q3. Set those keys to -1 and Q2 to 1.
# install.packages("psych") # Uncomment this if you haven't installed the psych package
library(psych)
keys <- c(-1,1,-1)

# Use the handy function from the pysch package
# mini is the minimum value and maxi is the maimum value
# mini and maxi can also be vectors if you have different scales
new_data <- reverse.code(keys,original_data,mini=1,maxi=5)
new_data
Run Code Online (Sandbox Code Playgroud)

这种方法的优点是您可以在一个函数中重新编码整个调查。缺点是你需要一个图书馆。股票 R 方法也更优雅。

仅供参考,这是我关于堆栈溢出的第一篇文章。长期听众,第一次来电。所以请就我的回答给我反馈。