【问题标题】:Replacing values with parts of strings from a label-list [R]用标签列表中的部分字符串替换值 [R]
【发布时间】:2020-02-24 02:57:22
【问题描述】:

我会尽量说这句话,请多多包涵。

我有包含 200 列的原始数据。 每列的值都被分配了数字,现在需要用它们的基础值替换。

对于每一列,基础值都会发生变化,这使得任务非常繁琐。

我收到了一个基础值列表,但一列的所有基础值都列在一个单元格中。 字符串可能看起来像 ["1 = 非常多 2 = 中等 3 = 不太多"] 我附上了一张图片,希望能帮助你理解。

On the left is my raw data and on the right the labels I have received

由于我有 200 列这种废话,因此 Excel 电子表格中的“搜索和替换”对于这项任务来说简直就是地狱。因此,我正在寻找一种方法来利用标签行并在 R 中实现自动化。

我只有一周的 R 经验,所以我不知道 R 解决此类任务的优势和局限性。

感谢任何阅读我作为小说家的处女作的人,我将不胜感激,干杯!

【问题讨论】:

    标签: r


    【解决方案1】:

    使用sapplyforcats::fct_collapse 应用于df 中的每一列

    library(rlang) #for !!!
    data.frame(sapply(names(df), 
                      function(x) forcats::fct_collapse(as.factor(df[[x]]), !!!lab[[x]])))
    
         Q1     Q2
    1   Yes    All
    2    NO   Some
    3 Maybe Rarely
    4 Maybe      4
    

    数据

    lab <- list(Q1=c('Yes'='1','NO'='2','Maybe'='3'), Q2=c('All'='1','Some'='2','Rarely'='3'))
    df <- structure(list(Q1 = c(1L, 2L, 3L, 3L), Q2 = 1:4), class = "data.frame", row.names = c(NA, -4L))
    

    【讨论】:

    • 谢谢,太好了!
    • 我不知道我只能选择一个答案,但你的答案是首选。对不起!
    【解决方案2】:

    您可以使用ifelse 语句:

    样本数据

    set.seed(111)
    df <- data.frame(
      Q1 = sample(1:3, 10, replace = T), 
      Q2 = sample(1:4, 10, replace = T), 
      Q3 = sample(1:3, 10, replace = T)
      )
    

    解决方案

    df$Q1_new <- ifelse(df$Q1==1, "Yes",
                        ifelse(df$Q1==2, "No", "Maybe"))
    df
       Q1 Q2 Q3 Q1_new
    1   2  1  3     No
    2   3  1  1  Maybe
    3   3  2  3  Maybe
    4   3  4  3  Maybe
    5   1  3  1    Yes
    6   3  4  3  Maybe
    7   1  2  1    Yes
    8   3  2  1  Maybe
    9   2  1  3     No
    10  1  4  1    Yes
    

    对于Q2Q3,以同样的方式继续:

    df$Q2_new <- ifelse(df$Q2==1, "All the time",
                        ifelse(df$Q2==2, "Some of the time",
                               ifelse(df$Q2==3, "Rarely", "Never")))
    df$Q3_new <- ifelse(df$Q3==1, "6 hours",
                        ifelse(df$Q3==2, "7 hours", "8 hours"))
    df
       Q1 Q2 Q3 Q1_new           Q2_new  Q3_new
    1   2  1  3     No     All the time 8 hours
    2   3  1  1  Maybe     All the time 6 hours
    3   3  2  3  Maybe Some of the time 8 hours
    4   3  4  3  Maybe            Never 8 hours
    5   1  3  1    Yes           Rarely 6 hours
    6   3  4  3  Maybe            Never 8 hours
    7   1  2  1    Yes Some of the time 6 hours
    8   3  2  1  Maybe Some of the time 6 hours
    9   2  1  3     No     All the time 8 hours
    10  1  4  1    Yes            Never 6 hours
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-03
      • 2021-03-01
      • 2013-11-03
      • 1970-01-01
      • 2023-03-20
      • 2019-03-09
      • 2020-07-28
      • 2020-03-08
      相关资源
      最近更新 更多