Wednesday, June 8, 2016

Example in R

The R-help mailing list has a posting guide which covers both asking and answering questions, including an example of generating data:
Examples: Sometimes it helps to provide a small example that someone can actually run. For example:
If I have a matrix x as follows:
  > x <- matrix(1:8, nrow=4, ncol=2,
                dimnames=list(c("A","B","C","D"), c("x","y"))
  > x
    x y
  A 1 5
  B 2 6
  C 3 7
  D 4 8
  >
how can I turn it into a dataframe with 8 rows, and three columns named 'row', 'col', and 'value', which have the dimension names as the values of 'row' and 'col', like this:
  > x.df
     row col value
  1    A   x      1
...
(To which the answer might be:
  > x.df <- reshape(data.frame(row=rownames(x), x), direction="long",
                    varying=list(colnames(x)), times=colnames(x),
                    v.names="value", timevar="col", idvar="row")
)
The word small is especially important. You should be aiming for a minimal reproducible example, which means that the data and the code should be as simple as possible to explain the problem.

##############################################################

Disclaimer: The Best answers from stackoverflow.com has been listed here.

No comments:

Post a Comment