我想根据一项调查的答案来衡量人们的情绪转变。调查提出了这样的问题:“0-5,你有多高兴:0不愉快,5非常快乐”或“0-5,你感觉有多大压力:0没有压力,5非常有压力”。数据如下:
我需要重新确定所有积极情绪问题的水平,所以: 5至0,4至1,3至2,2至3,1至4,0至5。
我试图编写一些代码,但我认为这是不正确的,因为到代码结束时,每0将再次从5改为0:
mood_cleaned$cheerful[mood_cleaned$cheerful==0] <- 5
mood_cleaned$cheerful[mood_cleaned$cheerful==1] <- 4
mood_cleaned$cheerful[mood_cleaned$cheerful==2] <- 3
mood_cleaned$cheerful[mood_cleaned$cheerful==3] <- 2
mood_cleaned$cheerful[mood_cleaned$cheerful==4] <- 1
mood_cleaned$cheerful[mood_cleaned$cheerful==5] <- 0代码也太长了,我有13个变量需要修改,所以必须有一个更简单的方法吗?谢谢!
发布于 2019-09-18 18:27:11
您的代码无法工作,因为您按顺序执行,而不是同时执行。您有几个选项,包括recode()、case_when等,但在您的示例中,最简单的操作对所有列都是相同的:
mood_cleaned$cheerful <- (mood_cleaned$cheerful-5)*-1
它应该做你想做的事情,例如(5-5)-1=0,(4-5)-1=1等等。
另一种选择是:
library(dplyr)
mood_cleaned %>%
mutate(cheerful = (cheerful-5)*-1)
# or this way
mood_cleaned %>%
mutate(cheerful = case_when( cheerful == 5 ~ 0,
cheerful == 4 ~ 1,
...)
# or with a fancy self-defined function
reverse_scale <- function(column){
new_value = (column-max(column))*-1
}
mood_cleaned$cheerful <- reverse_scale(mood_cleaned$cheerful)编辑:
我还看到您需要同时执行13个变量,所以这个解决方案应该是最好的:
library(dplyr)
# define universal function to reverse scaleS
reverse_scale <- function(column){
new_value = (column-max(column))*-1
}
# apply in dplyr logic to all columns
mood_cleaned %>%
mutate_at(.vars = 2:15, .funs = reverse_scale) # this works for columns 2 to 15, change numbers as needed
# or
mood_cleaned %>%
mutate_at(.vars = -1, .funs = reverse_scale) # this works for all columns except the first one发布于 2019-09-18 22:12:41
使用赋值矩阵,如这个答案中所示。这里不需要lapply,因为您只想操作一个列。
df1$cheerful <- c(4, 1, 5, 2, 0, 3)
df1
# X1 X2 X3 X4 cheerful
# 1 X X X X 4
# 2 X X X X 1
# 3 X X X X 5
# 4 X X X X 2
# 5 X X X X 0
# 6 X X X X 3
am <- matrix(c(0:5, 5:0),,2)
# [,1] [,2]
# [1,] 0 5
# [2,] 1 4
# [3,] 2 3
# [4,] 3 2
# [5,] 4 1
# [6,] 5 0
df1$cheerful <- am[match(df1$cheerful, am[, 1]), 2]
df1
# X1 X2 X3 X4 cheerful
# 1 X X X X 1
# 2 X X X X 4
# 3 X X X X 0
# 4 X X X X 3
# 5 X X X X 5
# 6 X X X X 2数据
df1 <- structure(list(X1 = c("X", "X", "X", "X", "X", "X"), X2 = c("X",
"X", "X", "X", "X", "X"), X3 = c("X", "X", "X", "X", "X", "X"
), X4 = c("X", "X", "X", "X", "X", "X")), class = "data.frame", row.names = c(NA,
-6L))发布于 2019-09-19 17:36:00
更简单
mood_cleaned$cheerful <- 5 - mood_cleaned$cheerful或者用于一个变量列表
for(this_mood in c("cheerful", "ecstatic")){
mood_cleaned[this_mood] = 5 - mood_cleaned[this_mood]
}https://stackoverflow.com/questions/57998601
复制相似问题