Printing the elements of a vector one per line in R

You know how R prints the elements of a vector horizontally?

> 1:5
[1] 1 2 3 4 5

Today I needed the elements printed one per line. After a bit of searching and hair-pulling, I stumbled upon the cat command:

> cat(1:5,sep="\n")
1
2
3
4
5

This is particularly useful when you need a line-by-line list of the variables in a data frame, which you can get with:

cat(names(dataframe),sep="\n")

To output the list directly to a file, use write instead of cat.

Advertisements

4 thoughts on “Printing the elements of a vector one per line in R

  1. THANK YOU! I just spent over an hour trying to figure out how to solve a problem in Excel and was beginning to conclude that I need to learn macros/Visual Basic.

    You saved me a lifetime of toil :D

    Best regards from Finland,

    Matti

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s