在不引入 NA 的情况下保存不等长度的数据
我有一个关于保存长度不等的数据帧的问题。有没有办法在不引入 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))
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我将创建一个列表并使用
write
写入文件。还有其他可能性(请参阅帮助文件中的?write
)。结果是
I would create a list and write to a file using
write
. There are other possibilities (see help file for?write
).The result is
数据框必须是矩形的。如果你想存储可变长度的数据,你需要使用列表。
您的数据是什么让您想要将其存储在数据框中?
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?