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

前端 未结 6 1653
太阳男子
太阳男子 2021-02-18 15:55

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 16:14

    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
    

提交回复
热议问题