Search code examples
rmatrixsavedataframenas

save data with unequal lengths without introducing NA's


I have a question about saving a dataframe with unequal lengths. Is there way to save table with variable lengths without introducing NA's or something? Here is an example with NA's but that is not what i want to save.

x <- list(matrix(c(1,4,3,2), ncol = 2,                   
dimnames = list(c("A","B"), NULL)),            
matrix(c(23,9,4,4,22,54), ncol = 2,                   
dimnames = list(c("C","D","E"), NULL))) 

out <- lapply(x, rownames) 
foo <- function(x, max, repl = NA) {     
if(length(x) == max)         
out <- x     
else {         
out <- rep(repl, max)         
out[seq_along(x)] <- x     
}     
out 
} 
out <- lapply(out, foo, max = max(sapply(out, length))) 
(out <- do.call(rbind, out))

Thank you


Solution

  • I would create a list and write to a file using write. There are other possibilities (see help file for ?write).

    myl <- list(a = letters[1:10], b = 1:3, c = "kaplah") #create some data
    
    # for every element in the list (`myl`), write that element to a file
    # and append if necessary. also, if list element is a character, write
    # to as many columns as there are characters.
    lapply(X = myl, FUN = function(x) {
        write(x, append = T, file = "test.txt", ncolumns = length(x))
    })
    

    The result is

    a b c d e f g h i j
    1 2 3
    kaplah