Home > OS >  writeLines to an outside file in a loop
writeLines to an outside file in a loop

Time:05-02

I'm fairly new to R, but basically I want to write certain parts of a data frame as text to an outside txt file. This is the code that I have,

for (i in 1:nrow(myd)) {
    if (i > nrow(myd)) {
      fileConn<-file("output.txt")
      writeLines(c(paste0(myd[i,2]),paste0(myd[i,4]), paste0(myd[i,11]),paste0(myd[i,8])), fileConn)
  } else
    close(fileConn)
}

This code only gives me the last row's data, is there a way to append each loop?

CodePudding user response:

Here is a way with cat. Write the columns and then call cat once again to write a newline character.
The condition in the loop will write the wanted columns of all even numbered rows. Tested with a mock data set, since there is none in the question.

myd <- sapply(1:11, \(x) rep(sprintf("column %d", x), 5))
myd <- as.data.frame(myd)
myd[[2]] <- letters[1:5]

output <- "output.txt"
fileConn <- file(output, open = "wt")
for (i in 1:nrow(myd)) {
  if(i %% 2 == 0) {
    cat(myd[i,2],  myd[i,4], myd[i,11], myd[i,8],
        file = fileConn, append = TRUE)
    cat("\n", file = fileConn, append = TRUE)
  }
}
close(fileConn)
readLines(output)
#> [1] "b column 4 column 11 column 8" "d column 4 column 11 column 8"

unlink(output)  # final clean-up

Created on 2022-05-01 by the reprex package (v2.0.1)

CodePudding user response:

Thanks everyone! I also found this to be satisfactory for my purposes:

  for (i in 1:nrow(myd)) {
  cat(paste0(myd[i,c(2,4,11,8)]), file = "my_file.txt", sep = "\n", append = TRUE)
  } 

Anyone knows how I can add a line of text (tag) before every columns text? Such as:

Type JOUR

Title A game for process mapping in office and knowledge work

Year 2021

Abstract The number of publications on ...

  • Related