Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print an R vector vertically

Tags:

r

I'm doing an analysis where I would like to change the printing of data from horizontal to vertical. For instance, when I do the following, here is the type of output I currently see:

> with(mtcars,sapply(split(mpg,cyl),mean))
       4        6        8 
26.66364 19.74286 15.10000 

I would like the output to be organized like this:

4    26.66364
6    19.74286
8    15.10000

Is there a way to achieve this?

like image 984
PearsonArtPhoto Avatar asked Aug 09 '14 23:08

PearsonArtPhoto


People also ask

How do I print a vector in R?

You can use the paste() function in R to print the contents of a vector as a single string. You can also specify a separator to use between the vector values with the collapse parameter of the paste() function. For example, let's convert the above vector to a string where the values are separated by a single space.

How do I view a vector in R?

Vector elements are accessed using indexing vectors, which can be numeric, character or logical vectors. You can access an individual element of a vector by its position (or "index"), indicated using square brackets. In R, the first element has an index of 1.


2 Answers

Try:

cat( paste( vector, collapse='\n' ) )

This essentially creates a string of vector elements and prints to console with newline character.

like image 178
Konstantin Timofeyuk Avatar answered Sep 16 '22 14:09

Konstantin Timofeyuk


You can use stack(),

with(mtcars, stack(sapply(split(mpg, cyl), mean)))
#    values ind
#1 26.66364   4
#2 19.74286   6
#3 15.10000   8

But aggregate() would probably be much nicer for this problem

aggregate(mpg ~ cyl, mtcars, mean)
#  cyl      mpg
#1   4 26.66364
#2   6 19.74286
#3   8 15.10000

Also, tapply() might be a better fit than sapply(), if you go that route.

stack(with(mtcars, tapply(mpg, cyl, mean)))
#    values ind
#1 26.66364   4
#2 19.74286   6
#3 15.10000   8

With sapply(), you're going to get a vector if the return values are only on one row, so you may want to use a different function for the calculations.

like image 22
Rich Scriven Avatar answered Sep 18 '22 14:09

Rich Scriven