Printing messages in R
Rachelly opened this issue · 1 comments
I want to print a message containing a few variables in a line, and some text in between. Is it possible to do it elegantly, as in C?
The closest solution I found is
x<-1
y<-2
print(c("x=",x,"y=",y))
[1] "x=" "1" "y=" "2"
But this is not so elegant, since the variables are not really characters and there are quote marks all arounf. Printing a list doesn't give the desirable results either:
print(list("x=",x,"y=",y))
[[1]]
[1] "x="
[[2]]
[1] 1
[[3]]
[1] "y="
[[4]]
[1] 2
Thanks,
Rachelly.
You can use the function message
:
x <- 1
y <- 'aas'
message('the variable x contains the value ', x, ' and y = ', y)
You can also use it in combination with the function str_out
in
pkgmaker
:
> x <- setNames(1:10, letters[1:10])
> message('My variable x contains: ', str_out(x) )
My variable x contains: 1L, 2L, ..., 10L
> message('My variable x contains: ', str_out(x, 5) )
My variable x contains: 1L, 2L, 3L, 4L, ..., 10L
> message('My variable x contains: ', str_out(x, Inf) )
My variable x contains: 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L
If you want to debug only, the function str
is convenient, especially for
-- not too long -- list
objects. It directly prints in stderr:
> x <- as.list(setNames(1:10, letters[1:10]))
> str(x)
List of 10
$ a: int 1
$ b: int 2
$ c: int 3
$ d: int 4
$ e: int 5
$ f: int 6
$ g: int 7
$ h: int 8
$ i: int 9
$ j: int 10