如何使用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 解释器打印您输入的表达式的值 - 应用.您可以将它分配到某个地方:
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屋!