Michael Gruenstaeudl Michael Gruenstaeudl - 3 months ago 15
R Question

Human-readable hard-coding dataframe in R

Assume that I wish to hard-coding a data frame in R.

my_df = data.frame(list(Name=c("foo", "bar", "baz", "qux"),
Result=c("Hello", NA, "foobar", "World")))


If the data frame was a lot longer (e.g., if it were to comprise dozens of rows), it would not be immediately intuitive that
baz
is associated with
foobar
(i.e., that these two values share the same row).

Is there a visually more human-readable way of hard-coding a data frame in R?

EDIT 1:

To clarify my question, I am not looking for an alternative way to format the hard-coding of the data frame (such as aligning the two rows by spacing out the words with whitespaces). Instead, what I am looking for is a way to, for example, specify the data frame rowwise.

Answer

You could use the frame_data() command from the tibble package.

For example:

dat <- frame_data(
  ~x, ~y,  ~z,
  "a", 2,  3.6,
  "b", 1,  8.5
)

It provides a hardcoding that is more 'by row' than the default data.frame entry method which is 'by column'.

Source