在下面的示例中,當我使用data.table's將數字以字符格式(即 .10)保存為 CSV 檔案時fwrite,Excel 將其顯示為數字而不是字串。
有沒有辦法以Excel可以識別為字串的字符格式保存數字?
我不是簡單地嘗試洗掉小數點前的 0 或保留尾隨的 0。
我想保持字串完整,就像它們在 R 中顯示的一樣(例如,.10 但沒有引號)。
dt <- data.table(a = ".10")
fwrite(dt, "example.csv")
# The saved CSV file opened in Excel shows the number 0.1, rather than the string .10
uj5u.com熱心網友回復:
Excel 在閱讀你想要的東西方面大多是腦殘。這是一種解決方法:
dat <- data.frame(aschr = c("1", "2.0", "3.00"), asnum = 1:3, hascomma = "a,b", hasnewline = "a\nb", hasquote = 'a"b"')
notnumber <- sapply(dat, function(z) is.character(z) & all(is.na(z) | !grepl("[^-0-9.]", z)))
needsquotes <- sapply(dat, function(z) any(grepl('[,\n"]', z))) & !notnumber
dat[needsquotes] <- lapply(dat[needsquotes], function(z) dQuote(gsub('"', '""', z), FALSE))
dat[notnumber] <- lapply(dat[notnumber], function(z) paste0("=", dQuote(z, FALSE)))
fwrite(dat, "iris.csv", quote = FALSE)
在 Excel 中產生以下透視圖。

其中大部分是預防性的:如果您非常了解您的資料并且您知道沒有任何資料包含逗號、引號或換行符,那么您可以去掉這些needsquotes部分。notnumber是感興趣的列。
最重要的是,我們通過強制將其作為 excel 公式來“欺騙”excel 使其保持字串。這可能不適用于其他電子表格(例如,Calc),我沒有測驗過。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/372782.html
上一篇:遍歷將一天的行分成幾分鐘的熊貓資料框的最安全方法是什么?
下一篇:使用Bash腳本編輯CSV檔案
