Sofy
Sofy

Reputation: 29

Head and Bottom text exporting data frame

I want to add Head and bottom txt to a data frame. I've searched 2 codes:

Head <- "  <BeginTimeSerie>"

Bottom <- " <EndTimeSerie>"

fn <- "data.txt" 
sink(fn) 
cat(Head) 
df1 
cat(Bottom) 
sink()


fn <- "data.txt"; writeLines(Head, fn); write.table(df1, fn,col.names
    = F, row.names = F, append=TRUE, quote=FALSE)

The first does add Head and Bottom txt but didn't export all the df1 file (it's huge, just export first 250 lines).

The second does export all the df1 file but I don't know how to add the bottom txt. I've tried different ways.

Upvotes: 0

Views: 52

Answers (1)

zx8754
zx8754

Reputation: 56004

Use write with append:

# example dataframe
df1 <- head(mtcars)

Head <- "  <BeginTimeSerie>"
Bottom <- " <EndTimeSerie>"

fn <- "data.txt"
write(Head, fn)
write.table(df1, fn, col.names = FALSE, row.names = FALSE, append = TRUE, quote = FALSE)
write(Bottom, fn, append = TRUE)

data.txt file:

  <BeginTimeSerie>
21 6 160 110 3.9 2.62 16.46 0 1 4 4
21 6 160 110 3.9 2.875 17.02 0 1 4 4
22.8 4 108 93 3.85 2.32 18.61 1 1 4 1
21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
18.7 8 360 175 3.15 3.44 17.02 0 0 3 2
18.1 6 225 105 2.76 3.46 20.22 1 0 3 1
 <EndTimeSerie>

Upvotes: 1

Related Questions