Reputation: 107
I need to prepare data for another (not R) program. The structure is a header = 1 row with 3 columns and then the data – few rows with 2 columns, and then another header (1x3) and data (nx2).. many times. I prepared the data with the headers and data combined with (‘’) at the last data column. But I need to get rid of this last column in the data portion because when I try to save it to file using write function, I get an extra tab. Following is an example data and the result I need to get. Can I write to a file with rows not in the same length?
tp5 <- data.frame(Depth_Date=double(5), Temp2=double(5), lt=integer(5))
tp5$Depth_Date <- c('2009-12-17',0,-1,-2,'2009-12-18')
tp5$Temp2 <- c(3,19.1,19.1,19,4)
tp5$lt <- c(2,'','','',2)
tp5
tp6 <- as.character(t(tp5))
write(tp6, file="tp6.dat", ncolumns=3, sep="\t")
The structure I want - (where '=>' means tab and {CRLF} means end of line.)
2009-12-17=>3.0=>2{CRLF}
0=>19.1{CRLF}
-1=>19.1{CRLF}
-2=>19.0{CRLF}
2009-12-18=>4.0=>2{CRLF}
The structure I get -
2009-12-17=>3.0=>2{CRLF}
0=>19.1=>{CRLF}
-1=>19.1=>{CRLF}
-2=>19.0=>{CRLF}
2009-12-18=>4.0=>2{CRLF}
i.e. with extra tab on the data part of the file.
Upvotes: 1
Views: 112
Reputation: 263411
Since tabs are considered "whitespace" characters you can remove trailing (or leading) tabs with the trimws
function and then write the resulting vectors to a file that are created with a line-by-line paste-operation:
x <- apply(tp5, 1, function(x) paste0(x,sep="\t",collapse=""))
trimws(x)
# note that the tabs have been removed
[1] "2009-12-17\t 3.0\t2" "0\t19.1" "-1\t19.1" "-2\t19.0"
[5] "2009-12-18\t 4.0\t2"
write( trimws(x), "~/Downloads/txt.txt" )
Upvotes: 1