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?
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.
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.
Try:
cat( paste( vector, collapse='\n' ) )
This essentially creates a string of vector elements and prints to console with newline character.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With