【问题标题】:Having trouble adding a string to the end of a vector that's in a list在列表中的向量末尾添加字符串时遇到问题
【发布时间】:2020-05-12 05:38:05
【问题描述】:
g = list(vegetable ="carrot", food=c("steak", "eggs"), numbers = c(4,2,1,7))

想知道如何在食物中添加其他元素吗? 尝试做食物

【问题讨论】:

  • g[["food"]] <- c(g[["food"]], "asparagus")。请参阅 ?"[" 进行冗长且技术性但有用的讨论。

标签: r list vector append


【解决方案1】:
g[["food"]] <- c(g[["food"]], "asparagus")

【讨论】:

    【解决方案2】:

    使用purrr 的一个选项可能是:

    modify_in(g, "food", ~ c(., "asparagus"))
    
    $vegetable
    [1] "carrot"
    
    $food
    [1] "steak"     "eggs"      "asparagus"
    
    $numbers
    [1] 4 2 1 7
    

    【讨论】:

      【解决方案3】:

      我们可以使用map_if

      library(purrr)
      map_if(g, names(g) == 'food', ~ c(.x, 'asparagus'))
      #$vegetable
      #[1] "carrot"
      
      #$food
      #[1] "steak"     "eggs"      "asparagus"
      
      #$numbers
      #[1] 4 2 1 7
      

      或与modifyList 来自base R

      modifyList(g, list(food = c(g[['food']], 'asparagus')))
      #$vegetable
      #[1] "carrot"
      
      #$food
      #[1] "steak"     "eggs"      "asparagus"
      
      #$numbers
      #[1] 4 2 1 7
      

      【讨论】:

        【解决方案4】:

        基础 R 解决方案

        g <- within(g,food <- c(food,"asparagus"))
        

        g <- within(g,food <- append(food,"asparagus"))
        

        这样

        > g
        $vegetable
        [1] "carrot"
        
        $food
        [1] "steak"     "eggs"      "asparagus"
        
        $numbers
        [1] 4 2 1 7
        

        【讨论】:

          猜你喜欢
          • 2016-07-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-15
          • 1970-01-01
          • 2021-11-05
          • 1970-01-01
          相关资源
          最近更新 更多