我想创建一个函数来更改给定CSV文件的特定单元格,并将它们保存回完全相同的格式。 我试图读取CSV文件并将其与编辑后的值一起写回来,但是在不误解逗号的情况下执行此操作的唯一方法是引用所有内容。 有没有办法编辑文件而不为每个值添加引号?
我的猜测是读取和写入CSV文件还有其他方法,而不是read.table
P.S。我想要编辑的csv文件不是按列分隔的值,而是具有相当模糊的格式(可能有不带引号,引用(主要是因为字符串中的逗号)字符串和整数在同一列/行中)
以下是我使用的代码:
editcell = function(id,
newvalue,
row,
col,
dbpath = "C:/data/",
add = FALSE
)
{
#READ
temptable = read.table(file = file(paste0(dbpath, id, ".csv")),
header = F,
sep = ",",
dec = ".",
fill = TRUE,
quote = "",
comment.char = "",
colClasses = "character",
# nrows = 400,
stringsAsFactors = F
);
cat("There are",nrow(temptable),"rows and",
ncol(temptable),"columns.");
#EDIT
if(add == TRUE) { temptable[x,y] = paste0(temptable[x,y],newvalue)}
else {temptable[x,y] = newvalue};
#WRITE
write.table(temptable,
file=paste0(dbpath, id,".csv"),
append = F,
quote = T,
sep=",",
eol = "\n",
na = "NA",
dec = ".",
row.names=F,
col.names=F,
qmethod = "double",
fileEncoding = ""
)
}