【问题标题】:Insert N string variables in one list/vector in R?在R中的一个列表/向量中插入N个字符串变量?
【发布时间】:2019-05-05 09:44:52
【问题描述】:

给定:

doc1 <- "Hearty Chicken Chorizo, Kale, Bean and Farro Soup"
doc2 <- "Spinach, Ham and Egg Whites Frittata – 2 Points"
doc3 <- "Lentil Tabouli"
doc4 <- "Individual Brussels Sprout & Potato Frittatas"
doc5 <- "Ahi Tuna Stacks with Ginger-Soy Dressing"
doc6 <- "Sagebrush Annie's Ventura County Cabernet Sauvignon & Merlot Ventura County"
doc7 <- "Lentil Chili"
doc8 <- "Slow Cooker Lentil Stew with Sausage"
doc9 <- "Spicy Lentil and Swiss Chard Soup"
doc10 <- "Tofu-Spinach Lasagne"
doc11 <- "Baked Ziti with Spinach"
doc12 <- "Mushroom, Spinach and Cheddar Wraps"
doc13 <- "Jamaican Jerk Pork Roast – Low Carb & Whole 30"
doc14 <- "Skinny Lasagna Rolls"
doc15 <- "Jamaican Jerk Pork Roast – Low Carb & Whole 30"
doc16 <- "Tofu & Broccoli Quinoa Stir-Fry"
doc17 <- "Chicken Fajita Stuffed Peppers"
doc18 <- "SketchBook Pinot Noir Wine"
doc19 <- "Chicken and Vegetable Soup"
doc20 <- "Manhattan Crab Chowder"
doc21 <- "Waterbrook Reserve Chardonnay"
doc22 <- "Chinese Beef and Broccoli"
doc23 <- "Easy Crab Curry"
doc24 <- "Waterbrook Reserve Chardonnay"

我想将它们全部放入一个 R 列表中:

as.list(c(doc1:doc24))

但我得到一个错误:

由 coercion 引入的 NAs 由 coercionError 引入 doc1:doc24 : NA/NaN 参数

我在这里错过了什么?

【问题讨论】:

  • mget(ls(pattern = "^doc"))
  • 正是我需要的!非常感谢你亲爱的@RonakShah

标签: r list vector


【解决方案1】:

我们可以使用pattern 来执行此操作,该pattern 匹配以“doc”开头的字符串(^)后跟一个或多个数字(\\d+)直到结尾($)字符串的

mget(ls(pattern = "^doc\\d+$"))

【讨论】:

    【解决方案2】:

    要获取环境中的对象,您可以使用 ls 和特定的 pattern

    mget(ls(pattern = "^doc"))
    

    或者您可以使用paste0 构造它们,然后使用mget

    mget(paste0("doc", 1:24))
    
    #$doc1
    #[1] "Hearty Chicken Chorizo, Kale, Bean and Farro Soup"
    
    #$doc2
    #[1] "Spinach, Ham and Egg Whites Frittata – 2 Points"
    
    #$doc3
    #[1] "Lentil Tabouli"
    
    #$doc4
    #[1] "Individual Brussels Sprout & Potato Frittatas"
    #...
    

    【讨论】:

      猜你喜欢
      • 2020-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-24
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多