在不引入 NA 的情况下保存不等长度的数据

发布于 11-27 20:17 字数 632 浏览 1 评论 0原文

我有一个关于保存长度不等的数据帧的问题。有没有办法在不引入 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

韶华倾负2024-12-04 20:17:44

我将创建一个列表并使用 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

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
丢了幸福的猪2024-12-04 20:17:44

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

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

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文