我有一个关于保存长度不等的数据帧的问题。是否可以在不引入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))
谢谢
答案 0 :(得分: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
答案 1 :(得分:2)
数据框必须是矩形的。如果要存储可变长度数据,则需要使用列表。
您希望将数据存储在数据框中的数据是什么?