简体   繁体   中英

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 (eg, if it were to comprise dozens of rows), it would not be immediately intuitive that baz is associated with foobar (ie, 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.

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

Another way would be to use read.table(text = "...") , eg

d <- read.table(text = "Name Result
                        foo  Hello
                        bar  NA
                        baz  foobar
                        qux  World", 
                header = TRUE, 
                stringsAsFactors = FALSE)
str(d)
# 'data.frame': 4 obs. of  2 variables:
#  $ Name  : chr  "foo" "bar" "baz" "qux"
#  $ Result: chr  "Hello" NA "foobar" "World"

I got this from a tweet by Noam Ross :

 readr::read_delim(
   '  Name  |   Result
    # -------------------
       foo  |   Hello
       bar  |   NA
       baz  |   foobar
       qux  |   World ',
   trim_ws = TRUE, comment="#", delim="|")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM