Reputation: 407
This might be a duplicate question, but I have been looking for an answer already for quite a while and could not find anything. If I run this short piece of code and print out description and results:
gear_query <- 5
mtcars_subset <- mtcars[mtcars$gear == gear_query, ]
paste("Cars with", gear_query, "gears:") ## description
print(mtcars_subset) ## results
I get this output to the console:
> paste("Cars with", gear_query, "gears:")
Cars with 5 gears:
> print(mtcars_subset)
mpg cyl disp hp drat wt qsec vs am gear carb
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.7 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.9 1 1 5 2
Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.5 0 1 5 4
Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.5 0 1 5 6
Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.6 0 1 5 8
How can I get R to print this information in one go, so that it looks like this, with nothing in between the description and the results:
> whatevercodethatdoesthetrick
Cars with 5 gears:
mpg cyl disp hp drat wt qsec vs am gear carb
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.7 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.9 1 1 5 2
Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.5 0 1 5 4
Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.5 0 1 5 6
Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.6 0 1 5 8
I tried it with cat():
cat("Cars with", gear_query, "gears:\n", mtcars_subset)
but got an error that 'list' cannot be handled by 'cat'. I also played around with paste(), but could not get it to work. Probably a pretty simple problem, but I can´t get to it ...
Upvotes: 1
Views: 169
Reputation: 56169
Using knitr:
library(knitr)
gear_query <- 5
kable(mtcars[ mtcars$gear == gear_query, ],
format = "pandoc",
caption = paste("Cars with", gear_query, "gears:"))
Table: Cars with 5 gears:
mpg cyl disp hp drat wt qsec vs am gear carb
--------------- ----- ---- ------ ---- ----- ------ ----- --- --- ----- -----
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.7 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.9 1 1 5 2
Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.5 0 1 5 4
Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.5 0 1 5 6
Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.6 0 1 5 8
Upvotes: 4