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,
dimna开发者_StackOverflowmes = 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
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
A data frame has to be rectangular. If you want to store variable length data you need to use a list.
What is it about your data that makes you want to store it in a data frame?
精彩评论