简体   繁体   English

将数据从 R 导出到 Excel

[英]Export data from R to Excel

I am writing codes to export database from R into Excel, I have been trying others codes including:我正在编写代码以将数据库从 R 导出到 Excel,我一直在尝试其他代码,包括:

write.table(ALBERTA1, "D:/ALBERTA1.txt", sep="\t")
write.csv(ALBERTA1,":\ALBERTA1.csv")
your_filename_in_R = read.csv("ALBERTA1.csv")
your_filename_in_R = read.csv("ALBERTA1.csv")
write.csv(df, file = "ALBERTA1.csv")
your_filename_in_R = read.csv("ALBERTA1.csv")
write.csv(ALBERTA1, "ALBERTA1.csv")
write.table(ALBERTA1, 'clipboard', sep='\t')
write.table(ALBERTA1,"ALBERTA1.txt")
write.table(as.matrix(ALBERTA2),"ALBERTA2.txt")
write.table(as.matrix(vecm.pred$fcst$Alberta_Females[,1]), "vecm.pred$fcst$Alberta_Females[,1].txt")
write.table(as.matrix(foo),"foo.txt")
write.xlsx(ALBERTA2, "/ALBERTA2.xlsx")
write.table(ALBERTA1, "D:/ALBERTA1.txt", sep="\t").

Other users of this forum advised me this:该论坛的其他用户建议我:

write.csv2(ALBERTA1, "ALBERTA1.csv")
write.table(kt, "D:/kt.txt", sep="\t", row.names=FALSE)

在此处输入图像描述

You can see on the pictures the outcome I have got from this codes above.您可以在图片上看到我从上面的代码中得到的结果。 But this numbers can't be used to make any further operations such as addition with other matrices.但是这个数字不能用于进行任何进一步的操作,例如与其他矩阵的加法。

Has someone experienced this kind of problems?有人遇到过这种问题吗?

Another option is the openxlsx -package.另一种选择是openxlsx It doesn't depend on and can read, edit and write Excel -files.它不依赖于 ,可以读取、编辑和写入Excel文件。 From the description from the package:从包装的描述中:

openxlsx simplifies the the process of writing and styling Excel xlsx files from R and removes the dependency on Java openxlsx 简化了从 R 编写和设置 Excel xlsx 文件样式的过程,并消除了对 Java 的依赖

Example usage:示例用法:

library(openxlsx)

# read data from an Excel file or Workbook object into a data.frame
df <- read.xlsx('name-of-your-excel-file.xlsx')

# for writing a data.frame or list of data.frames to an xlsx file
write.xlsx(df, 'name-of-your-excel-file.xlsx')

Besides these two basic functions, the openxlsx -package has a host of other functions for manipulating Excel -files.除了这两个基本功能之外, openxlsx还有许多其他用于操作Excel文件的功能。

For example, with the writeDataTable -function you can create formatted tables in an Excel -file.例如,使用writeDataTable函数,您可以在Excel文件中创建格式化表格。

Recently used xlsx package, works well.最近用的xlsx包,效果不错。

library(xlsx)
write.xlsx(x, file, sheetName="Sheet1")

where x is a data.frame其中 x 是一个 data.frame

writexl , without Java requirement: writexl ,没有Java要求:

# install.packages("writexl")
library(writexl)
tempfile <- write_xlsx(iris)

The WriteXLS function from the WriteXLS package can write data to Excel. WriteXLS包中的WriteXLS函数可以将数据写入 Excel。

Alternatively, write.xlsx from the xlsx package will also work.或者,来自xlsx包的write.xlsx也可以使用。

One could also use the readODS package.也可以使用readODS包。 Granted it doesn't produce an .xlsx , but Excel can read Open Document Spreadsheet (ODS) / LibreOffice files too.当然它不会生成.xlsx ,但 Excel 也可以读取 Open Document Spreadsheet (ODS) / LibreOffice 文件。

require(readODS)

tmp = file.path(tempdir(), 'iris.ods')
write_ods(iris, tmp)

If I might offer an alternative, you could also save your dataframe in a regular csv file, and then use the "get data" function within Excel to import the dataframe.如果我可以提供替代方案,您还可以将数据框保存在常规csv文件中,然后使用 Excel 中的“获取数据”功能导入数据框。 This worked like a charm for me, and you need not bother with any excel packages in R.这对我来说就像一个魅力,你不必为 R 中的任何 excel 包而烦恼。

Here is a way to write data from a dataframe into an excel file by different IDs and into different tabs (sheets) by another ID associated to the first level id.这是一种通过不同 ID 将数据从数据帧写入 excel 文件并通过与第一级 ID 关联的另一个 ID 写入不同选项卡(工作表)的方法。 Imagine you have a dataframe that has email_address as one column for a number of different users, but each email has a number of 'sub-ids' that have all the data.想象一下,您有一个数据框,其中email_address作为许多不同用户的一列,但每封电子邮件都有许多包含所有数据的“子 ID”。

data <- tibble(id = c(1,2,3,4,5,6,7,8,9), email_address = c(rep('aaa@aaa.com',3), rep('bbb@bbb.com', 3), rep('ccc@ccc.com', 3)))

So ids 1,2,3 would be associated with aaa@aaa.com .因此 ids 1,2,3将与aaa@aaa.com相关联。 The following code splits the data by email and then puts 1,2,3 into different tabs.以下代码通过电子邮件拆分数据,然后将1,2,3放入不同的选项卡中。 The important thing is to set append = True when writing the .xlsx file.重要的是在编写.xlsx文件时设置append = True


temp_dir <- tempdir()

for(i in unique(data$email_address)){
    
  data %>% 
    filter(email_address == i) %>% 
    arrange(id) -> subset_data
  
  for(j in unique(subset_data$id)){
    write.xlsx(subset_data %>% filter(id == j), 
      file = str_c(temp_dir,"/your_filename_", str_extract(i, pattern = "\\b[A-Za-z0- 
       9._%+-]+"),'_', Sys.Date(), '.xlsx'), 
      sheetName = as.character(j), 
      append = TRUE)}
 
  }

The regex gets the name from the email address and puts it into the file-name.正则表达式从电子邮件地址中获取名称并将其放入文件名中。

Hope somebody finds this useful.希望有人觉得这很有用。 I'm sure there's more elegant ways of doing this but it works.我确信有更优雅的方法可以做到这一点,但它确实有效。

Btw, here is a way to then send these individual files to the various email addresses in the data.frame .顺便说一句,这是一种将这些单独的文件发送到data.frame中的各种电子邮件地址的方法。 Code goes into second loop [j]代码进入第二个循环[j]

  send.mail(from = "sender@sender.com",
            to = i,
          subject = paste("Your report for", str_extract(i, pattern = "\\b[A-Za-z0-9._%+-]+"), 'on', Sys.Date()),
          body = "Your email body",
          authenticate = TRUE,
          smtp = list(host.name = "XXX", port = XXX,
                      user.name = Sys.getenv("XXX"), passwd = Sys.getenv("XXX")),
          attach.files = str_c(temp_dir, "/your_filename_", str_extract(i, pattern = "\\b[A-Za-z0-9._%+-]+"),'_', Sys.Date(), '.xlsx'))


I have been trying out the different packages including the function:我一直在尝试不同的包,包括功能:

install.packages ("prettyR") 

library (prettyR)

delimit.table (Corrvar,"Name the csv.csv") ## Corrvar is a name of an object from an output I had on scaled variables to run a regression. delimit.table (Corrvar,"Name the csv.csv") ## Corrvar是我在缩放变量上运行回归的输出中的对象名称。

However I tried this same code for an output from another analysis (occupancy models model selection output) and it did not work.但是,我为另一个分析的输出(占用模型模型选择输出)尝试了相同的代码,但它不起作用。 And after many attempts and exploration I:经过多次尝试和探索,我:

  • copied the output from R ( Ctrl + c )从 R 复制输出( Ctrl + c
  • in Excel sheet I pasted it ( Ctrl + V )在 Excel 表中我粘贴了它( Ctrl + V
  • Select the first column where the data is选择数据所在的第一列
  • In the "Data" vignette, click on "Text to column"在“数据”小插图中,单击“文本到列”

  • Select Delimited option, click next选择分隔选项,点击下一步

  • Tick space box in "Separator", click next勾选“分隔符”中的空格框,点击下一步

  • Click Finalize (End)点击完成(结束)

Your output now should be in a form you can manipulate easy in excel.您现在的输出应该是您可以在 excel 中轻松操作的形式。 So perhaps not the fanciest option but it does the trick if you just want to explore your data in another way.因此,这可能不是最好的选择,但如果您只想以另一种方式探索数据,它就可以解决问题。

PS. PS。 If the labels in excel are not the exact one it is because Im translating the lables from my spanish excel.如果 excel 中的标签不是确切的标签,那是因为我从我的西班牙语 excel 中翻译了标签。

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

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