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

后端 未结 6 1686
逝去的感伤
逝去的感伤 2021-02-18 20:15

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:47

    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
    

提交回复
热议问题