[英]Function write.table() is converting my character column to numeric when exporting to excel. How can I prevent this?
I have a dataframe in a similar way:我有一个 dataframe 以类似的方式:
Material c1 c2 c3 c4 c5 c6
1 0111 30 44 24 25 52 27
2 0112 19 70 93 23 68 100
3 1124 22 NA 79 18 133 143
4 2389 79 NA NA 81 60 NA
5 3480 57 8 95 62 NA 90
6 0134 350 60 50 302 44 4
Here I am forcing as character type, but in my real dataframe it alredy is.在这里我强制作为字符类型,但在我真正的 dataframe 中它已经是。
df['Material']=as.character(df['Material'])
sapply(df,mode)
write.table(df, paste(".\\exports\\", "dummy.csv", sep = ""), sep = ";", dec = ",",row.names=F)
The problem is that when I export to excel, my Material column becomes numeric and I loose the 0 in the beginning that is a part of the material code description.问题是,当我导出到 excel 时,我的 Material 列变成了数字,我丢失了开头的 0,它是材料代码描述的一部分。 My rows get sorted and I would like to have them in the original position.
我的行已排序,我希望将它们放在原始 position 中。 Is there a way of preventing this to happen?
有没有办法防止这种情况发生? To keep my Material column as character when exporting?
导出时将我的材料列保持为字符?
In case you want to replicate it, I tried to create a dummy version:如果您想复制它,我尝试创建一个虚拟版本:
df <- data.frame(Material = c('0111','0112','1124','2389','3480'),
actual_202009 = c(30,19,22,79,57),
actual_202010 = c(44,70,NA,NA,8),
actual_202011 = c(24,93,79,NA,95),
pred_202009 = c(25,23,18,81,62),
pred_202010 = c(52,68,133,60,NA),
pred_202011 = c(27,100,143,NA,90))
As mentioned in the comments:如评论中所述:
This works.这行得通。
library(openxlsx)
write.xlsx(df, file = "dummy.xlsx")
Even though the data in your csv has quotes around the Material column, excel likes to think for you and not honour the character quotes.尽管 csv 中的数据在 Material 列周围有引号,但 excel 喜欢为您考虑而不尊重字符引号。 Now you could use libreoffice with calc.
现在您可以将 libreoffice 与 calc 一起使用。 This will open the text import option where you can tell it that the first column is text and it will retain the correct format for the Material column.
这将打开文本导入选项,您可以在其中告诉它第一列是文本,并且它将保留 Material 列的正确格式。
But the easiest is just to use the above code.但最简单的就是使用上面的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.