2017-09-30 36 views
1

目前,我正在将我的Likert类型比例重新编码为数字值。但是,我在这个数据集中有很多不同比例的项目。例如:Q2.1_1:Q2.1_16是一个Likert量表,它具有与其他调查不同的关键字。目前,我手动输入每个重新编码是这样的:重新编码多个Likert标度 - 任何包?

final$Q2.1_1rc <- as.numeric(recode(
    final$Q2.1_1, 
    "Very slightly or not at all" = 1, 
    "A little"     = 2, 
    "Moderately"     = 3, 
    "Quite a bit"     = 4, 
    "Extremely"     = 5 
)) 

我那么C/P并继续改变变量的名称。但是,我有一个大的数据集这样算下来,手动将是累赘。任何人都可以用更短的方式来帮助我解决这个问题吗?有包可以帮助吗?也许是一个功能?

谢谢!

回答

0

一次可以重新编码多个变量的方法是使用dplyr包中的mutate_at函数。

实例数据

library(dplyr) 
set.seed(123) 
resp <- c("Very slightly or not at all", "A little", "Moderately", "Quite a bit", "Extremely") 
final <- tibble(Q2.1_1 = sample(resp, 6, replace = TRUE), 
       Q2.2_1 = sample(resp, 6, replace = TRUE)) 

解决方案
假设你想开始与final都有"Q2"在他们的变量名的开头的变量,你可以这样做:

final %>% 
    mutate_at(vars(starts_with("Q2")), 
      funs("rc" = recode(., 
           "Very slightly or not at all" = 1, 
           "A little"     = 2, 
           "Moderately"     = 3, 
           "Quite a bit"     = 4, 
           "Extremely"     = 5))) 

#> # A tibble: 6 x 4 
#>      Q2.1_1  Q2.2_1 Q2.1_1_rc Q2.2_1_rc 
#>       <chr>  <chr>  <dbl>  <dbl> 
#> 1     A little Moderately   2   3 
#> 2     Quite a bit Extremely   4   5 
#> 3     Moderately Moderately   3   3 
#> 4     Extremely Moderately   5   3 
#> 5     Extremely Extremely   5   5 
#> 6 Very slightly or not at all Moderately   1   3 

official documentation中所述,dplyr开始的最佳位置是,的R数据科学书,而与mutate_at的使用相关的具体示例可以在here找到。