如何使用apply,cat和print而不使用NULL [英] How to use apply, cat and print, without getting NULL
问题描述
我正在尝试将cat()用作apply()中的函数.我可以几乎使R做我想做的事,但是在返回的末尾我得到一些(对我来说)非常令人困惑的NULL.这是一个愚蠢的示例,以突出显示我所得到的.
I am trying to use cat() as functions inside apply(). I can almost make R do what I want, but I'm getting some very confusing (to me) NULLS at the end of the return. Here is a silly example, to highlight what I'm getting.
val1 <- 1:10
val2 <- 25:34
values <- data.frame(val1, val2)
apply(values, 1, function(x) cat(x[1], x[2], fill=TRUE))
R中的这个有效"接受并运行,但是我不理解结果.
This "works" in that R accepts it and it runs, but I don't understand the results.
> apply(values, 1, function(x) cat(x[1], x[2], fill=TRUE))
1 25
2 26
3 27
4 28
5 29
6 30
7 31
8 32
9 33
10 34
NULL
但是,我想得到:
> apply(values, 1, function(x) cat(x[1], x[2], fill=TRUE))
1 25
2 26
3 27
4 28
5 29
6 30
7 31
8 32
9 33
10 34
那么,如何删除最终的NULL?
So, how do I remove that final NULL?
推荐答案
NULL是R解释器,它打印您键入的表达式的值-apply.您可以将其分配到某个地方:
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.
这篇关于如何使用apply,cat和print而不使用NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!