简体   繁体   English

使用 write.table 将列表写入 R 中的 a.dat

[英]Writing a list into a .dat in R using write.table


I'm trying to write the number list that this loop produces into a file. 我正在尝试将此循环产生的数字列表写入文件。 I using the code below I have been able to do that, but the output is not exactly what I'm looking for. 我使用下面的代码已经能够做到这一点,但 output 并不是我想要的。 I know I need to use write.table and it needs to be saved as a.dat 我知道我需要使用 write.table 并且需要将其保存为 a.dat

Can anyone tell me why the "x" is printing in between each line? 谁能告诉我为什么“x”在每行之间打印? **What I am getting in the file:** **我在文件中得到的内容:**
x X
1800 1800
x X
1804 1804
x X
1808 1808
x X
etc... ETC...

What I want:我想要的是:
1804 1804
1808 1808
1812 1812
etc... ETC...

 years <- seq(1800,2020) for (i in years){ i_div_400 <- i%%400 if (i_div_400 == 0 & (i%%4 == 0 && i%%100.= 0)){ write,table(i. "file,dat", append=TRUE, sep=",", quote=FALSE) } }

The reason why you get "x" in the output is because that is the default column names when using write.table .在 output 中获得“x”的原因是因为这是使用write.table时的默认列名。 If you don't want to include column name in the output use col.names = FALSE and it will print only numbers in the output.如果您不想在 output 中包含列名,请使用col.names = FALSE ,它将仅打印 output 中的数字。

years <- seq(1800,2020)

for (i in years){
  i_div_400 <- i%%400
  if (i_div_400 == 0 || (i%%4 == 0 && i%%100 != 0)){
    write.table(i, "file.dat", append=TRUE, sep=",", 
               row.names=FALSE, quote=FALSE, col.names = FALSE)  
  }
}

Also this can be written in a vectorised way without a loop.这也可以在没有循环的情况下以矢量化方式编写。

write.table(years[years %% 400 == 0 | (years %% 4 == 0 & years %%100 != 0)], 
          "file.dat", sep=",", row.names=FALSE, quote=FALSE, col.names = FALSE)  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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