【问题标题】:how to print data to the console and read it back in?如何将数据打印到控制台并将其读回?
【发布时间】:2016-05-02 13:13:55
【问题描述】:

我有一些数据打印到控制台:

> head(mydata)

V1                  V2        V3
1 29228 2005-01-01 00:00:00 12345
2 29228 2005-01-01 00:10:00 23456
3 29228 2005-01-01 00:20:00 34567
4 29228 2005-01-01 00:30:00 45678

我想与同事分享这些数据。如果我可以用我的代码将数据保存在 r 脚本中,而不必共享单独的数据文件,那就太好了。

是否可以将这些数据从字符串中读取到 R 中,例如

> df <- read("
   V1                  V2        V3
   1 29228 2005-01-01 00:00:00 12345
   2 29228 2005-01-01 00:10:00 23456
   3 29228 2005-01-01 00:20:00 34567
   4 29228 2005-01-01 00:30:00 45678
")

【问题讨论】:

    标签: r


    【解决方案1】:

    如果您想与其他 R 用户共享您的数据。最好使用 dput 命令。 例如:

    df <- read.table(text = 
    "V1                  V2        V3 V4
    1 29228 2005-01-01 00:00:00 12345
    2 29228 2005-01-01 00:10:00 23456
    3 29228 2005-01-01 00:20:00 34567
    4 29228 2005-01-01 00:30:00 45678", header = TRUE)
    
    dput(df)
    
    structure(list(V1 = c(29228L, 29228L, 29228L, 29228L), V2 = structure(c(1L, 
    1L, 1L, 1L), .Label = "2005-01-01", class = "factor"), V3 = structure(1:4, .Label = c("00:00:00", 
    "00:10:00", "00:20:00", "00:30:00"), class = "factor"), V4 = c(12345L, 
    23456L, 34567L, 45678L)), .Names = c("V1", "V2", "V3", "V4"), class = "data.frame", row.names = c("1", 
    "2", "3", "4"))
    

    此输出将保留数据帧的原始结构和格式,并采用更简洁的形式。读回数据很简单:

    newdf<- structure(list(V1 = c(29228L, 29228L, 29228L, 29228L), V2 = structure(c(1L, 
    1L, 1L, 1L), .Label = "2005-01-01", class = "factor"), V3 = structure(1:4, .Label = c("00:00:00", 
    "00:10:00", "00:20:00", "00:30:00"), class = "factor"), V4 = c(12345L, 
    23456L, 34567L, 45678L)), .Names = c("V1", "V2", "V3", "V4"), class = "data.frame", row.names = c("1", 
    "2", "3", "4"))
    

    这也是在 stackoverflow 上提供示例的首选方法!

    【讨论】:

      【解决方案2】:

      是的,尽管您有 4 列。

      df <- read.table(text = 
      "V1                  V2        V3 V4
      1 29228 2005-01-01 00:00:00 12345
      2 29228 2005-01-01 00:10:00 23456
      3 29228 2005-01-01 00:20:00 34567
      4 29228 2005-01-01 00:30:00 45678", header = TRUE)
      

      你也可以这样做

      df = head(mydata)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-30
        相关资源
        最近更新 更多