Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

apply

cat

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))

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

But, I want to get:

> 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

So, how do I remove that final NULL?

like image 904
Choens Avatar asked Oct 13 '10 17:10

Choens


1 Answers

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.

like image 163
Spacedman Avatar answered Oct 15 '22 04:10

Spacedman