[R] insert/copy skipped lines to output

Muhammad Rahiz muhammad.rahiz at ouce.ox.ac.uk
Sun Mar 28 18:51:18 CEST 2010


Dear Jannis,

Thanks for the tip. It works but I'd like to improve on the way I did it.

x <- array(1:50,dim=c(10,10)) # data

h1 <- c("ncols                180") # header, line 1
h2 <- c("nrows               290") # header, line 2
h3 <- c("xllcorner           -200000") # header, line 3
h4 <- c("yllcorner           -200000") # header, line 4
h5 <- c("cellsize             5000") # header, line 5
h6 <- c("NODATA_value  NA") # header, line 6

h0 <- rbind(h1,h2,h3,h4,h5,h6)

write(ho,"file.txt")
write.table(x,"file.txt",row.names=FALSE,col.names=FALSE,append=TRUE)

The header should display as;

ncols                   180
nrows                  290
xllcorner              -200000
yllcorner              -200000
cellsize                 5000
NODATA_value     NA





Jannis wrote:
> Hallo,
>
> have a look at the documentation of the different output functions
> (write(),cat(),write.table()). Most of them have an argument like
> "append". If you set this to TRUE, your command adds the lines you are
> writing into the file to the lines already existent in that file. So if
> you run this write() command first with your additional data (header
> data) and then with the "real" data and append=TRUE, your information
> ends up in the same file.
>
>
> HTH
> Jannis
>
>
> Muhammad Rahiz schrieb:
>   
>> Hello all,
>>
>> I'd like some advise on this. When I read my files, I pass the 
>> argument, skip=6, to skip 6 lines of header information. After 
>> performing the desired calculations, I have the output. Now I want to 
>> copy the 6 lines of skipped information to the output.
>>
>> What I've been doing so far is to use a shell script (i.e. the cat 
>> function)  to copy the header information to the output file. This 
>> means I need 2 additional files, namely a file containing the header 
>> information only, and the shell script to run the the function.
>>
>> Is there a direct way to perform this in R?
>>
>> The following forms the main component of my R script;
>>
>> x <- as.matrix(read.table("file.txt",skip=6))
>> y <- x*2
>> write.table(y,"output.txt",row.names=FALSE,col.names=FALSE)
>>
>>
>> Thanks
>>
>> Muhammad
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide 
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>>     
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list