代码之家  ›  专栏  ›  技术社区  ›  Luis

tidyverse-集成mutate select和case when to likert scales

  •  1
  • Luis  · 技术社区  · 8 年前

    我是 时髦诗 用户和我面临着执行我想象的简单命令的困难。

    我有一个数据集,其中一些变量类似于比例,现在,我想为这些特定的变量集分配一些文本标签。要做到这一点,我想最好的过程是 突变 然后 选择 我想改变哪些变量,然后, 告诉R什么是新值 .

    在我看来,这是合乎逻辑的。然而,在我想做的事情和我正在创建的R代码之间有一个桥梁。

    我希望有人能帮我解决这个问题。

    下面的代码是一个可重复的示例:

    library(tidyverse)
    ds <- data.frame(sex=c(0,1), age=rnorm(n = 100, mean = 7, sd=2),
                     question1_1 = sample(1:5),
                     question1_2 = sample(1:5),
                     question1_3 = sample(1:5),
                     question1_4 = sample(1:5),
                     question1_5 = sample(1:5))
    ds <- ds %>% mutate(
      select %>% starts_with("question1_") %>% 
      case_when(. == 1 ~ "Strongly disagree",
                . == 2 ~ "Disagree",
                . == 3 ~ "Neutral",
                . == 4 ~ "Agree",
                . == 5 ~ "Strongly agree"))
    

    我没有发现之前有任何消息询问相同的问题,因此,我创建了这个新线程。请让我知道此消息是否重复以排除它。

    非常感谢。

    2 回复  |  直到 8 年前
        1
  •  3
  •   akrun    8 年前

    我们可以用在 mutate_at

    ds %>%
       mutate_at(vars(starts_with('question')), 
             funs(case_when(.==1 ~ "Strongly disagree",
                            .==2 ~ "Disagree",
                            .==3 ~ "Neutral",
                            .==4 ~ "Agree",
                            .==5 ~ "Strongly agree")))
    

    但是,这可以变得更简单,因为值是整数,所以 vector 对于相同顺序的字符串,我们希望使用整数值作为索引进行更改

    v1 <- c('Strongly disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly agree')
    ds %>%
       mutate_at(vars(starts_with('question')),
             funs(v1[.]))
    
        2
  •  1
  •   moodymudskipper    8 年前

    您还可以使用以下因素:

    library(tidyverse)
    ds %>%
      mutate_at(vars(starts_with('question')), factor, 
                     labels= c("Strongly disagree","Disagree","Neutral","Agree", "Strongly agree")) %>%
      head
    
    #   sex      age       question1_1       question1_2       question1_3       question1_4       question1_5
    # 1   0 6.518414             Agree           Neutral          Disagree           Neutral             Agree
    # 2   1 4.972210           Neutral          Disagree    Strongly agree Strongly disagree Strongly disagree
    # 3   0 6.422792 Strongly disagree    Strongly agree             Agree          Disagree    Strongly agree
    # 4   1 9.839967          Disagree             Agree           Neutral    Strongly agree           Neutral
    # 5   0 7.518809    Strongly agree Strongly disagree Strongly disagree             Agree          Disagree
    # 6   1 8.446730             Agree           Neutral          Disagree           Neutral             Agree
    

    在基础中翻译 R :

    cols_lgl <- startsWith(names(ds),"question")
    ds[cols_lgl] <- lapply(ds[cols_lgl],factor, labels= c("Strongly disagree","Disagree","Neutral","Agree", "Strongly agree"))
    
    推荐文章