2

I have been struggling for a while with this issue in R:

let's say that I have a for loop which runs over 9 data files. In this loop, I extract a short vector from a longer vector. Easy.

After that,still during the loop, I want to fill a matrix with the freshly extracted short vector and save the matrix to a file. Not easy, because none of the short vectors have the same length. To avoid the problem, I tried to directly save (still in the loop) the vectors directly in a .csv file with write.table() and append=TRUE, but R appends all the 9 vectors in the same column, when I would like to have 9 columns. Does anything like by.column=TRUE exist?

One way or another, I only want to have my 9 short vectors in 9 columns in a data file. It looks to me that I am not too far with the second solution.

Has anyone an idea how to finally finish this little programm? I would greatly appreciate.

Thank you for your time Michel

user1317221_G
  • 15,087
  • 3
  • 52
  • 78
michel ducos
  • 21
  • 1
  • 2

1 Answers1

1

I'd suggest that you adjust your workflow slightly, doing something like this:

  1. First collect all of the vectors in a single R list object.

  2. Still within R, massage the list of vectors into a matrix or data.frame. (This will be easier once you have extracted all of the vectors, and know the length of the longest one.)

  3. Only then write out the resultant table with a single call to write.table or write.csv.

Here's an example:

## Set up your for() loop or lapply() call so that it returns a list structure 
## like 'l'
l <- list(a=1:9, b=1:2, c=1:5)

## Make a matrix from the list, with shorter vectors filled out with ""s
n <- max(sapply(l, length))
ll <- lapply(l, function(X) {
    c(as.character(X), rep("", times = n - length(X)))
})
out <- do.call(cbind, ll)                 

## Then output it however you'd like. (Here are three options.)
# write.csv(out, file="summary.csv")
# write.csv(out, file="summary.csv", quote=FALSE)
# write.table(out, file="summary.txt", row.names=FALSE, quote=FALSE, sep="\t")
Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455