简体   繁体   中英

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) } }

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)  

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