简体   繁体   中英

Add header and footer to data in write.table()

I have several hundred data files and I need to add a header (start of the data in a file) and footer (end of the data in a file) to each file in r like following:

Header:

line1
line2
line3

likewise, I have few lines that I like to add the footer at the end of each data file

footer:

line1
line2
line3

while writing a table in r with write.table(). Can someone suggest a simple solution? Thanks

Perhaps something like this:

lapply( c('dobjt1', 'dobjct2', 'other3'),
  function(x) { 
    name <- paste0( x, ".txt")
    write(c(line1,line2,line3), file=name)
    out <- get(x); Need to use `get` when working with character values
    write.table(out, file=name, append=TRUE)
    write(c(line1,line2,line3), file=name, append=TRUE)
  })

Adding steps to @42- s solution to read a list of files from disk and assign their file names as the data frame names leads to a complete, working solution.

We'll use the Pokémon data from Alex Barradas Pokémon Stats data set from kaggle.com as our example.

download.file("https://github.com/lgreski/PokemonData/raw/master/pokemonData.zip",
              "pokemonData.zip",mode="wb",method="wininet")

unzip("pokemonData.zip")

thePokemonFiles <- list.files("./pokemonData",
                              full.names=FALSE)[1:3] # subset to first 3 files

pokemonData <- lapply(thePokemonFiles,function(x) {
  data <- read.csv(paste("./pokemonData/",x,sep=""))
  # set input file name as object name so file list can be used in lapply() for write
  assign(x,data,parent.env(environment()))
  NULL # null return to avoid duplicating data frames in output list
})

header <- c("header 1","header 2","header 3")
footer <- c("footer 1","footer 2","footer 3")


lapply(thePokemonFiles, function(x) {
  name <- paste0(x, ".txt")
  write(header, file = name)
  write.table(get(x), file = name, append = TRUE)
  write(footer, file = name, append = TRUE)
})

...and the first few lines of the resulting text file for the first generation Pokémon is:

在此处输入图片说明

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