代码之家  ›  专栏  ›  技术社区  ›  ah bon

使用R中的apply循环和打印列表元素

  •  0
  • ah bon  · 技术社区  · 3 年前

    我可以使用for循环来循环列表中的每个元素:

    data <- list("Hello", c("USA", "Red", "100"), c("India", "Blue", "76"))
    for(i in data){
      print(i)}
    

    结果:

    [1] "Hello"
    [1] "USA" "Red" "100"
    [1] "India" "Blue"  "76"
    

    我想知道使用的等效方法是什么 apply 从基R或中的其他函数 purrr 包裹

    0 回复  |  直到 3 年前
        1
  •  1
  •   AndrewGB    3 年前

    具有 purrr ,您可以使用 walk :

    library(purrr)
    walk(data, print)
    
    [1] "Hello"
    [1] "USA" "Red" "100"
    [1] "India" "Blue"  "76" 
    
        2
  •  1
  •   Brian Montgomery    3 年前

    管道到invisible()将避免显示结果列表,只会产生打印副作用。

    lapply(data, print) |> invisible()
    [1] "Hello"
    [1] "USA" "Red" "100"
    [1] "India" "Blue"  "76"