8

When posting a question in R, I see basically 3 approaches to represent a data frame:

#1

df <- data.frame("a" = 1:5, "b" = 6:10, "c" = 11:15)

#2

a  b  c
1  6 11
2  7 12
3  8 13
4  9 14
5 10 15

#3

(The output for dput)

structure(list(a = 1:5, b = 6:10, c = 11:15), .Names = c("a", 
"b", "c"), row.names = c(NA, -5L), class = "data.frame")

In my opinion, #2 is the best for visualization and allows quick answers for simple questions. On the other hand, it is the worst if working with the data is needed.

What are the pros and cons for each approach? Is any of them considered better than the others?

2
  • related: meta.stackoverflow.com/questions/267730/…
    – rene
    Commented Jan 25, 2017 at 20:57
  • 7
    Include what is needed to explain the problem (2) and to reproduce it (1 or 3). You don't have to pick one.
    – user6655984
    Commented Jan 25, 2017 at 22:14

2 Answers 2

8

You have two goals here:

  • illustrate the data so the problem can be understood more easily at a first glance

  • provide minimal reproducible data for your example and for testing

For such a simple dataset alternative #1 would be best. It is reproducible and anyone with experience in R can visualize the data easily.

Whenever such visualization is not so easy, you should also provide #2.

You should provide #3 for data that is not easy to recreate with short code or if you have imported data and are unable to recreate it without the original data source.

So, for the specific example: preferably #1, but #2 + #3 would also be okay.

7

When someone posts #2, I usually put it in R using:

read.table(text = 
"a  b  c
1  6 11
2  7 12
3  8 13
4  9 14
5 10 15", header=TRUE)

So, you can try posting it directly like this. It shows the structure as in #2 and allows for quick import into R.

2
  • There are even packages that facilitate this approach, but it is still a nuisance and you can't be sure that you end up with exactly the same object as OP. Printing does not preserve all properties of the data.
    – Roland
    Commented Jan 26, 2017 at 15:31
  • Nice answer! For simple datasets this is a great alternative. But as stated by @Roland in the above comment, it might not be appropriate for every case. Commented Jan 26, 2017 at 16:39

Not the answer you're looking for? Browse other questions tagged .