How to use apply, cat and print, without getting NULL

情到浓时终转凉″ 提交于 2019-12-03 14:17:48

The NULL is the R interpreter printing the value of the expression you typed in - the apply. You can either assign it somewhere:

junk = apply(values, 1, function(x) cat(x[1], x[2], fill=TRUE))

in which case it wont get printed, or wrap it in 'invisible':

invisible(apply(values, 1, function(x) cat(x[1], x[2], fill=TRUE)))

Note that its only when you run this interactively that each line is printed, if it's in a function you won't see it.

Do you really need the apply() to loop through your content?

> print(values, row.names=FALSE)
 val1 val2
    1   25
    2   26
    3   27
    4   28
    5   29
    6   30
    7   31
    8   32
    9   33
   10   34

As Dirk pointed out this is not the way to print thing in R. Usually you would assign the result to a variable and then print it. No side effects, so to say.

Your problem stems from the cat functions, which prints to the terminal as a side effect, but returns NULL.

Try

a <- cat("blabla\n")  
a

If you really want to use apply for printing, there are two solutions. Wrap into invisible call

invisible(apply(values, 1, function(x) invisible(cat(x[1], x[2], fill=TRUE))))

or, just assign the result (NULL) to a temporary value

t <- apply(values, 1, function(x) invisible(cat(x[1], x[2], fill=TRUE)))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!