簡體   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