简体   繁体   中英

Writing variables to “.txt” file in R

I am writing variables to a ".txt" file in . 的“ .txt”文件。 I write the following code:

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)

I run the code twice and got

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

My question is why the 6-th variable changed to the next line since I didn't use any "\\n". Another question, is there any way in to control the digits of the written variables such as 有什么方法可以控制写入变量的数字,例如

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

in ?

write function has ncolumns parameter that is defaulted to 5 for non-character vectors:

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

try:

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)

, which produces single line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM