简体   繁体   English

将数据从 R 导出到 excel

[英]Exporting data to excel from R

How can I export my data from R to Excel without changing number format?如何在不更改数字格式的情况下将我的数据从 R 导出到 Excel?

My dataset is composed of percentage numbers but get formatted as decimal numbers:我的数据集由百分比数字组成,但被格式化为十进制数字:
For.eg: 67% is printed as 0.67 .例如: 67%打印为0.67

Is there any code to paste the numbers as they are in my source files?是否有任何代码可以粘贴我的源文件中的数字?

Your data is probably type character?您的数据可能是类型字符?

Anyway, try using openxlsx library to format excel sheet.无论如何,尝试使用 openxlsx 库格式化 excel 表。 Here is a simple example:这是一个简单的例子:

library(openxlsx)

df <- data.frame(pct1 = c(0.07, 0.22), pct2 = c(0.07, 0.22))

#header style
hs <- createStyle(textDecoration = "bold", wrapText = FALSE, halign = "center", valign = "center")
#style
s1 <- createStyle(numFmt = "0.0%") #1 decimal place
s2 <- createStyle(numFmt = "PERCENTAGE") #2 decimal places (default)

wb <- createWorkbook("")
addWorksheet(wb, "test")
writeData(wb, 1, df, startCol = 1, startRow = 1, headerStyle = hs)
#autosize imena emailov
setColWidths(wb, sheet = 1, cols = 6:8, widths = "auto")

addStyle(wb, 1, style = s1, rows = 2:(nrow(df)+1), cols = 1, gridExpand = FALSE)
addStyle(wb, 1, style = s2, rows = 2:(nrow(df)+1), cols = 2, gridExpand = FALSE)

saveWorkbook(wb, paste0("test.xlsx"), overwrite = TRUE) 

Well, it depends on what type are your columns in the data frame.好吧,这取决于数据框中的列是什么类型。 "dplyr::write_csv" should do the job, but note you have to convert the columns as type character to keep the structure in excel “dplyr::write_csv” 应该可以完成这项工作,但请注意您必须将列转换为类型字符以将结构保留在 excel

enter image description here在此处输入图像描述

enter image description here在此处输入图像描述

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

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