简体   繁体   English

R中人类可读的硬编码数据帧

[英]Human-readable hard-coding dataframe in R

Assume that I wish to hard-coding a data frame in R. 假设我希望在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). 如果数据帧更长(例如,如果它包括几十行),则bazfoobar相关联(即,这两个值共享同一行)并不是直接的直观。

Is there a visually more human-readable way of hard-coding a data frame in R? 是否有一种在视觉上更加人性化的方式对R中的数据帧进行硬编码?

EDIT 1: 编辑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. 您可以使用frame_data()从命令tibble包。

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'. 它提供的硬编码比'by column'的默认data.frame入口方法更“按行”。

Source 资源

Another way would be to use read.table(text = "...") , eg 另一种方法是使用read.table(text = "...") ,例如

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 : 我从Noam Ross推文中得到了这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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