R:通过函数重新编码(失败)

时间:2018-09-23 11:39:12

标签: r

我正在尝试编写用于重新编码变量的函数(因为我必须多次执行相同的任务)。

任何人都可以告诉我为什么此代码失败吗?

mydata <- data.frame(s_18 = c(1,2,3,4,5,4,5,4,3,4,3,2,1,2,3,1,2,3,4,5,4,3,2,1,2,1,2,3,1), 
                     s_19 = c(2,1,2,3,1,2,3,4,5,4,3,2,1,2,1,2,3,1,5,4,2,3,1,2,3,2,1,4,5))

# Recoding from numeric into character (works fine)
mydata$s_18new[mydata$s_18 == 1] <- "Agree"
mydata$s_18new[mydata$s_18 == 2] <- "Partly Agree"
mydata$s_18new[mydata$s_18 == 3] <- "Neutral"
mydata$s_18new[mydata$s_18 == 4] <- "Partly disagree"
mydata$s_18new[mydata$s_18 == 5] <- "Disagree"

mydata$s_18new

# But I have to perform this task about 50 times - so I thought a function would be a good solution
my_function <- function(new_var_name, old_var_name) {
  mydata$new_var_name[mydata$old_var_name == 1] <- "Agree"
  mydata$new_var_name[mydata$old_var_name == 2] <- "Partly Agree"
  mydata$new_var_name[mydata$old_var_name == 3] <- "Neutral"
  mydata$new_var_name[mydata$old_var_name == 4] <- "Partly disagree"
  mydata$new_var_name[mydata$old_var_name == 5] <- "Disagree"
}

my_function(s_19new, s_19)

1 个答案:

答案 0 :(得分:1)

您也可以使用sapply进行此操作,所需的键入次数更少:

# create a dictionary of mapping
temp <- list('1'='Agree', '2'='Partly Agree', '3'='Neutral', '4'='Partly Disagree', '5'='Disagree')

# map the values
mydata$s_19new <- sapply(mydata$s_19, function(x) temp[[as.character(x)]])