将 R 数据框导出到 CSV - 如何引用所有列,包括数字列?

Exporting R data frame to CSV - How can I quote all columns including numeric ones?

我需要编写一个包含所有列的 CSV,但是

write.table(param, file=outputFile, row.names=FALSE, col.names=TRUE, sep=",", dec=".", quote=TRUE)

这样写:

"maxit","size","decay","resulado","filename"
"1",10000,6,5e-05,0,996363636363636,"result-1.csv"

还有 dec="."仍然为小数写逗号。

我需要的:

"maxit","size","decay","resulado","filename"
"1","10000","6","5e-05","0.996363636363636","result-1.csv"

有小费吗?

谢谢。

来自?write.table:

Only columns which have been converted to character will be quoted if specified by ‘quote’.

所以你可以先转换为字符,然后写入文件。此外,由于您想编写一个 CSV,而不是使用 write.table 并分别弄乱每个参数,您可以只使用 write.csv,它默认使用 dec="."sep=","。例如如果您的数据框是 DF:

DF[] <- lapply(DF, as.character)
write.csv(DF, "foo.csv")

您可以在调用 format() 的结果上调用 write.table() 函数:

write.table(format(df))

这会将所有列转换为字符向量,还可以让您控制格式化的方式。

> sapply(format(mtcars), mode)
        mpg         cyl        disp          hp        drat          wt        qsec          vs          am        gear        carb 
"character" "character" "character" "character" "character" "character" "character" "character" "character" "character" "character"