How to suppress part of the output from `lapply()`?

前端 未结 2 1706
南方客
南方客 2021-01-13 12:53

I want to use lapply() to print all the elements that I have inside of a list. The following code does that, but the output produced is strange.



        
相关标签:
2条回答
  • 2021-01-13 13:11

    An option is invisible

    invisible(lapply(N.seq, print))
    #[1] 1
    #[1] 2
    #[1] 3
    #[1] 4
    #[1] 5
    

    If we want to convert the vector to list,

    as.list(N.seq)
    
    0 讨论(0)
  • 2021-01-13 13:24

    The *applys always return something, so lapply will print everything and then give you some output. What you want is called a side effect, which is when the function affects things outside of its own local scope. You could enclose your *apply functions in invisible() to suppress the output, but the purrr package has a function designed explicitly to handle side effects:

    library(purrr)
    walk(N.seq, print)
    
    #### OUTPUT ####
    
    [1] 1
    [1] 2
    [1] 3
    [1] 4
    [1] 5
    
    0 讨论(0)
提交回复
热议问题