当前位置: 动力学知识库 > 问答 > 编程问答 >

Create empty csv file in R

问题描述:

I have an R script that runs a set of functions on multiple datasets and creates a set of concentration-response models. What I would like to do is save out the model parameters and other results to a csv file.

My plan is to have the script create an empty csv file and then as the script progresses, results are appended to that csv file. Every time the script is run I would like the results to be overwritten.

I've tried to create an empty file using

system("copy /y NUL results.csv > NUL")

to create the file, but the file is not created. This command (i.e., copy/y NUL results.csv > NUL) works properly when run directly in the Windows terminal.

Am I missing something simple? System is Windows XP.

Thanks all!

网友答案:

Is there anything wrong with file.create(), which is portable across operating systems?

file.create("my.csv")
# [1] TRUE

You can then append to the file, e.g. using the append=TRUE argument to write.table(), perhaps like this:

df <- data.frame(a=1:4, b=4:1)
write.table(df, file="my.csv", sep=",", row.names=FALSE, append=TRUE)
write.table(df, file="my.csv", sep=",", row.names=FALSE, 
            col.names=FALSE, append=TRUE)

EDIT If you will be doing a ton of writes to each file, it can save considerable time to open a connection to the file once, and only close it when you're done. If that is not the case, the approach above works just fine.

网友答案:

Because it is shell command you should use shell instead of system.

shell("copy /y NUL results.csv > NUL")

EDIT. More portable solution:

cat(NULL,file="results.csv")
网友答案:

how about just

echo > results.csv
网友答案:

Use truncate.

f <- file("my.csv", open="w")
truncate(f)
分享给朋友:
您可能感兴趣的文章:
随机阅读: