使用sink()和cat()写入R中的csv

时间:2017-10-18 23:22:00

标签: r sink

有没有简单的方法,在R中使用sink()写入csv文件,写入前两个单元格为空的行,第三个单元格有一个特定的字符串?这不是那么简单,我正在努力。我尝试了以下内容:

# this approach writes all 5 numbers in one (the first) line with 2 spaces between each number
sink('myfile.csv')
for(i in 1:5) {
  cat(c(' ', ' ', i))
}
sink()


# this approach writes each number on its own line, but in the 1st column with 2 spaces the number
sink('myfile.csv')
for(i in 1:5) {
  cat(c(' ', ' ', i), '\n')
}
sink()

# this approach throws an error
sink('myfile.csv')
for(i in 1:5) {
  a = data.frame(` ` = '', `  ` = '', `Requested Access?` = '')
  cat(a, '\n')
}
sink()

要验证,我上面示例中的所需输出将是一个CSV文件,其中每个数字分别为1,2,3,4,5,每个都在C列中。对此有任何帮助!

1 个答案:

答案 0 :(得分:2)

您需要在空格中添加逗号:

sink('myfile.csv')
for(i in 1:5) {
  cat(c(' ,', ' ,', i), '\n')
}
sink()

或者,使用write.table来避免for循环:

write.table(data.frame(` `=" ", ` `= "", ` ` = 1:5),
          row.names=FALSE,
          col.names = FALSE, 
          file = "myfile.csv",
          sep=",")