rlistfilefor-loopwrite.table

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. I know I need to use write.table and it needs to be saved as a .dat

Can anyone tell me why the "x" is printing in between each line? **What I am getting in the file:**
x
1800
x
1804
x
1808
x
etc...

What I want:
1804
1808
1812
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)  
  }
}

Solution

  • The reason why you get "x" in the output is because that is the default column names when using 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.

    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)