2

我有一个关于保存长度不等的数据框的问题。有没有办法在不引入 NA 或其他东西的情况下保存可变长度的表?这是一个 NA 的例子,但这不是我想要保存的。

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))

谢谢

4

2 回答 2

3

我会创建一个列表并使用write. 还有其他可能性(参见帮助文件?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))
})

结果是

a b c d e f g h i j
1 2 3
kaplah
于 2011-08-05T12:15:45.377 回答
2

数据框必须是矩形的。如果要存储可变长度数据,则需要使用列表。

您的数据是什么让您想要将其存储在数据框中?

于 2011-08-05T09:52:00.333 回答