【问题标题】:save data with unequal lengths without introducing NA's在不引入 NA 的情况下保存长度不等的数据
【发布时间】:2011-08-05 09:44:31
【问题描述】:

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

谢谢

【问题讨论】:

    标签: r matrix save dataframe nas


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 不一定是数据框,我需要保存一个行数不相等的表。这可能吗?
      • @Lisann,您可以将列表(一次每个元素)写入文件(请参阅?write,注意append = TRUE)。
      • @Roman 你能写一个例子吗?因为我不知道你到底是什么意思.. 感谢您的回答
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-05
      • 1970-01-01
      • 2013-02-11
      • 1970-01-01
      • 2014-10-21
      • 1970-01-01
      相关资源
      最近更新 更多