【问题标题】:How to write a header vector plus dataframe using cat()如何使用 cat() 编写标头向量和数据帧
【发布时间】:2021-04-14 12:24:02
【问题描述】:

类似:writing a data.frame using cat 但是这是关于附加到文件,我想写一个新文件。

我有一个标头和一个数据框,我想使用 cat() 将其写入文件:

header <- "This is the top row,\n
           where the values are:"

df <- data.frame(val1= runif(3), val2 = runif(3))

# Write to file
cat(header, df, 
    file = "path/to/file.txt", 
    sep = "\n")

给出错误:

Error in cat(header, df, file = "path/to/file.txt", sep = "\n") : 
  argument 2 (type 'list') cannot be handled by 'cat'

上面写着list,但是class(df)显示它是一个dataframe,我把这个dataframe做成和上面的基本一样。

我将如何打印它,使它看起来像这样(df 由任何类型的空格分隔):

文件.txt:

This is the top row
where the values are:
0.63138 0.70402 
0.50136 0.61327
0.10447 0.26874
...

完整的文件最多可以包含 101 行的数据框。

【问题讨论】:

  • 数据帧在内部实现为列表,列表的元素是列向量

标签: r dataframe io cat


【解决方案1】:

您可以将catwrite.table 一起使用。

header <- "This is the top row,\n where the header info is.\n"

cat(header, file = 'file.txt')
write.table(df, 'file.txt', append = TRUE, row.names = FALSE, col.names = FALSE)

【讨论】:

    【解决方案2】:

    试一试:

    cat(
      paste0(
        header, 
        paste0(
          trimws(
            gsub(
              "^\\d+", 
              "", 
              capture.output(
                print(
                  df
                  )
                )
              ), 
            "left"), 
          collapse = "\n")
        ),
    file = "path/to/file.txt", 
    sep = "\n")
    

    数据:

    header <- "This is the top row, \n where the header info is.\n\n"
    
    df <- data.frame(val1= runif(3), val2 = runif(3))
    

    【讨论】:

    • 这几乎可以工作,除了我不想要每行前面的行号和列名,只需要值
    • 它适用于前 10 个实例,但任何超过 10 的行号都不起作用
    【解决方案3】:

    kable 可以格式化数据帧并返回cat 可以写入文件的向量。它还可以进行所需的舍入和对齐。

    library(knitr)
    
    # store the header text as a vector for better spacing
    header <- c("This is the top row",
                "where the header info is.")
    
    df <- data.frame(val1= runif(3), val2 = runif(3))
    
    # convert the data frame into a simple  markdown text table
    text <- kable(df, digits = 5, format = "simple", col.names = NULL)
    
    # remove the extra markdown formatting 
    text <- text[!grepl("---", text)]
    
    # write to your file
    cat(header, text, sep = "\n", file = "path/to/file.txt")
    

    结果将包含

    This is the top row,
    where the header info is.
     0.23796   0.20287
     0.67260   0.41703
     0.53092   0.26330
    

    【讨论】:

    • 这是目前为止效果最好的,只是我不想要标题名称。只是价值观。但这已用 text[c(-1,-2)] 而不是 text[-2] 解决
    • col.names = NULL 选项添加到kable() 函数调用是删除列名的另一种方法。我会更新帖子以删除它们
    猜你喜欢
    • 2021-11-15
    • 2014-10-20
    • 2017-11-11
    • 1970-01-01
    • 2014-07-29
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 2019-02-27
    相关资源
    最近更新 更多