繁体   English   中英

使用write.table复制粘贴数据框时,如何在output表格上方添加一行文字?

[英]How to add a row of text above the output table when using write.table to copy and paste a data frame?

假设我们有以下名为data的数据框,由下面的代码生成:

> data
  ID Period Values
1  1      1      5
2  1      2     10
3  1      3     15
4  2      1     12
5  2      2      0
6  2      3      2
7  3      1      4
8  3      2     -8
9  3      3      3

data <- 
  data.frame(
    ID = (c(1,1,1,2,2,2,3,3,3)),
    Period = as.numeric(c(1, 2, 3, 1, 2, 3, 1, 2, 3)),
    Values = as.numeric(c(5, 10, 15, 12, 0, 2, 4, -8, 3))
  )

接下来,我们在 base R 中使用以下简单代码将data复制并粘贴到 Excel 工作表中:

write.table(x = data,
            file = "clipboard",
            sep = "\t",
            row.names = FALSE,
            col.names = TRUE
  )

当复制/粘贴数据到 Excel 时,我想在表格的正上方插入一行描述表格的文本(例如:表格名称是“数据” ),如下图所示。

如何修改上面的代码以在表格上方插入文本行? 在基地 R 最好?

在此处输入图像描述

单独剪贴板

writeLines(
  c("table name is mtcars",
    capture.output(write.table(mtcars[1:3,], sep = "\t", row.names = FALSE))),
  "clipboard")

...然后粘贴到 Excel。我过去遇到过数据嵌入问题(嵌入选项卡等)的问题,也许链中的某些内容(包括“我”)没有正确处理所有事情。

在 windows 上,可以将writeLines(.., "clipboard")替换为writeClipboard ,但 function 仅是 windows。 在其他操作系统上,可以安装clipr package 用于剪贴板读/写。

使用文件

writeLines("table name is mtcars", con = "somefile.csv")
write.table(mtcars[1:3,], "somefile.csv", row.names = FALSE, append = TRUE, sep = ",")
# Warning in write.table(mtcars[1:3, ], "somefile.csv", row.names = FALSE,  :
#   appending column names to file

(不能使用write.csv ,因为它不能容忍append=TRUE ,抱怨attempt to set 'append' ignored 。)

结果文件:

table name is mtcars
"mpg","cyl","disp","hp","drat","wt","qsec","vs","am","gear","carb"
21,6,160,110,3.9,2.62,16.46,0,1,4,4
21,6,160,110,3.9,2.875,17.02,0,1,4,4
22.8,4,108,93,3.85,2.32,18.61,1,1,4,1

它在 Excel 中打开为

excel快照

暂无
暂无

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

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