【问题标题】:Why is R making my CSV files larger? [duplicate]为什么 R 使我的 CSV 文件变大? [复制]
【发布时间】:2015-03-03 17:24:16
【问题描述】:

我正在尝试读取一系列 CSV 文件并准备它们以供以后添加。在附加它们之前,我需要创建一个列来告诉我它们来自哪个原始文件。在这种情况下,它们是企业的部门。我目前正在使用数字代码来减少文件大小的增加量。

从读取的 CSV 文件到写入的 CSV 文件,我的文件大小出现了很大的跳跃。在不添加“分区”列(下面注释掉)的情况下,我的文件大小增加如下:

19,111 KB 到 24,458 KB; 71,331 KB 至 89,989 KB; 33,919 KB 到 42,898 KB

谁能解释一下?有没有办法改进代码?

谢谢!

insert.division <- function(fileroot, divisionname){

    ext <- ".csv"
    file <- paste(fileroot, ext, sep = "")
    data <- read.csv(file, header = TRUE, stringsAsFactors = FALSE)
    #data$division <- divisionname
    write.csv(data, file = paste(fileroot, "_adj3", ext, sep = ""),
        row.names = FALSE)

}

files <- c(
    "file1",
    "file2",
    "file3",
    "file4",
    "file5"
)

divisions <- c(1:5)

mapply(insert.division, fileroot = files, divisionname = divisions)

【问题讨论】:

  • 使用文本编辑器比较输入和输出文件。我有一些想法,但这里没有可重现的例子。
  • @Roland:感谢您的建议。这似乎是在所有字符串周围添加双引号以及添加 NA 的问题。有任何解决这个问题的方法吗?或者当我合并 CSV 时它不会影响性能?

标签: r csv


【解决方案1】:

原因似乎是 write.csv 为所有字符串添加引号,而 Excel 仅将它们用于包含逗号的字符串。更多信息:
Delete "" from csv values and change column names when writing to a CSV

【讨论】:

    猜你喜欢
    • 2021-10-24
    • 1970-01-01
    • 2021-08-16
    • 2012-06-14
    • 1970-01-01
    • 1970-01-01
    • 2010-10-27
    • 1970-01-01
    • 2021-08-25
    相关资源
    最近更新 更多