【问题标题】:R replace numeric values in nested lists with values from a vectorR用向量中的值替换嵌套列表中的数值
【发布时间】:2021-10-08 13:13:17
【问题描述】:

我有一个如下数据集,我之前使用which 函数获得的。

data <- data.frame(id = c(123, 124, 125, 126, 127))

data <- data %>% mutate(a = list(c(11:12), c(11,12,15), integer(0), c(1,2,3), 4),
                        b = list(c(16,18), c(5,6,7), c(8,9,10), 14, 1))

我需要用labels中的对应值替换a和b中的数字值:

labels <- c("apple", "orange", "pear", "grapes", "lemon", "strawberry",
            "watermelon", "kiwi", "pineapple", "melon", "tangerine", "prune", 
            "cucumber", "tomato", "onion", "pepper", "garlic")

所以 1 应该变成苹果,2 是橙色,如果没有数字,单元格应该保持空白

【问题讨论】:

    标签: r list replace


    【解决方案1】:

    怎么样?

    data %>%
      rowwise() %>%
      mutate(
        a = list(labels[unlist(a)]),
        b = list(labels[unlist(b)])
      ) %>%
      ungroup()
    

    【讨论】:

      【解决方案2】:

      对于基础 R 中的多个此类列,您可以使用 lapplyrelist 来维护列表结构。

      data[-1] <- lapply(data[-1], function(x) relist(labels[unlist(x)], x))
      data 
      #   id                       a                             b
      #1 123        tangerine, prune                    pepper, NA
      #2 124 tangerine, prune, onion lemon, strawberry, watermelon
      #3 125                                kiwi, pineapple, melon
      #4 126     apple, orange, pear                        tomato
      #5 127                  grapes                         apple   
      

      【讨论】:

        【解决方案3】:

        我们可以使用map

        library(purrr)
        library(dplyr)
        data %>%
            mutate(across(a:b,  ~map(.,  ~ labels[.x])))
           id                       a                             b
        1 123        tangerine, prune                    pepper, NA
        2 124 tangerine, prune, onion lemon, strawberry, watermelon
        3 125                                kiwi, pineapple, melon
        4 126     apple, orange, pear                        tomato
        5 127                  grapes                         apple
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-10-11
          • 1970-01-01
          • 2017-07-31
          • 2023-03-27
          • 1970-01-01
          • 2016-04-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多