Home > Blockchain >  Loop and print element of list using apply in R
Loop and print element of list using apply in R

Time:01-24

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?

CodePudding user response:

With purrr, you can use walk:

library(purrr)
walk(data, print)

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

CodePudding user response:

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"
  •  Tags:  
  • Related