简体   繁体   中英

Loop and print element of list using apply in R

I could loop each element from list using for loop:

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

Result:

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

I wonder what's the equivalent method using apply from base R or other functions in purrr package?

Piping to invisible() will avoid showing the resulting list and give just the print side effect.

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

With purrr , you can use walk :

library(purrr)
walk(data, print)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM