2016-05-31 129 views
0

我正在將變量寫入R中的「.txt」文件。我寫了下面的代碼:將變量寫入「.txt」文件中R

textfile=file.path("tuning_parameter.txt"); 
printer = file(textfile,"a+"); 
write(c(V1,V2,V3,V4,V5,V6),textfile,sep = " ",append = TRUE); 
write("\n", textfile, append=TRUE) 
close(printer) 

我運行代碼兩次,並得到了

1 0.02301807 0.5829662 1.391419 0.0452473 
0.07409543 
1 0.02301807 0.5829662 1.391419 0.0452473 
0.07409543 

我的問題是,爲什麼在6個變量改變到下一行,因爲我沒有使用任何「\ N」。另一個問題,是在有- [R任何方式來控制寫入的變量,如

fprintf(fid, '%s %10.4f %10.4f \n',V1,V2,V3); 

的位數MatLab的

+0

爲什麼不只是'write.table'? – alistaire

+0

@alistaire我需要文本文件。 – sopin

+0

這就是'write.table':空格分隔的文本文件,如果你喜歡,你可以保存爲.txt。 – alistaire

回答

1

write函數具有ncolumns參數默認爲5非字符載體:

write(x, file = "data", 
     ncolumns = if(is.character(x)) 1 else 5, 
     append = FALSE, sep = " ") 

嘗試:

V1 <- 1 
V2 <- 0.02301807 
V3 <- 0.5829662 
V4 <- 1.391419 
V5 <- 0.0452473 
V6 <- 0.07409543 
textfile=file.path("tuning_parameter.txt"); 
printer = file(textfile,"a+"); 
write(c(V1,V2,V3,V4,V5,V6), textfile,sep = " ",append = TRUE, ncolumns = 6); 
write("\n", textfile, append=TRUE) 
close(printer) 

,產生單線。

+0

謝謝!這正是答案。 – sopin