in R, can I stop print(cat(“”)) from returning NULL? and why does cat(“foo”) return foo>

前端 未结 6 2319
耶瑟儿~
耶瑟儿~ 2021-02-18 19:44

If I enter

print(cat(\"\"))

I get

NULL

I want to use cat() to print out the progress of an R sc

6条回答
  •  无人共我
    2021-02-18 20:19

    For this, I often use writeLines(), in combination with strwrap(), and paste() to combine say the loop value if I'm printing out info on the current iteration. strwrap() handles wrapping long lines as required, and writeLines() means I don't have to remember to add a "\n" on the end of my cat() calls.

    > writeLines(strwrap("a very very very very long long long long long long long long string, that is too wide for the current pager width"))
    a very very very very long long long long long long long long string,
    that is too wide for the current pager width
    

    Here is an example using it to print out an iteration indicator:

    for(i in 1:1000) {
        if(isTRUE(all.equal(i %% 100, 0)))
            writeLines(strwrap(paste("Iteration", i)))
        ## do something
    }
    

    Gives:

    > for(i in 1:1000) {
    +     if(isTRUE(all.equal(i %% 100, 0)))
    +         writeLines(strwrap(paste("Iteration", i)))
    +     ## do something
    + }
    Iteration 100
    Iteration 200
    Iteration 300
    Iteration 400
    Iteration 500
    Iteration 600
    Iteration 700
    Iteration 800
    Iteration 900
    Iteration 1000
    

提交回复
热议问题