如何将长度不等的列表元素保存到文件输出

3
我有一个包含1000个元素的列表,每个元素都由不同长度(平均长度约为6000)的其他列表组成。我需要将其保存到.csv或更好地是.txt文件中。由于这是一个非常大的对象,所以我通过一个简单的例子来展示问题。
给定以下列表,它由2个列表组成,这两个列表分别由4个和6个元素组成,如下所示:
[[1]]
[[1]][[1]]
[1] 7 3 5 4 8

[[1]][[2]]
[1] 5 7 8

[[1]][[3]]
[1] 1 5

[[1]][[4]]
[1] 6


[[2]]
[[2]][[1]]
[1] 1 7 3 4 5 9

[[2]][[2]]
[1] 5 9 2 1

[[2]][[3]]
[1] 6 2 4

[[2]][[4]]
[1] 6 1

[[2]][[5]]
[1] 5 9

[[2]][[6]]
[1] 6

我需要将这个列表保存为.csv或者更好的.txt文件,以便于维护列表编号的引用。例如,前两个数字代表列表的顺序,如下所示:

1, 1, 7, 3, 5, 4, 8
1, 2, 5, 7, 8
1, 3, 1, 5                
1, 4, 6

2, 1, 1, 7, 3, 4, 5, 9
2, 2, 5, 9, 2, 1
2, 3, 6, 2, 4
2, 4, 6, 1
2, 5, 5, 9
2, 6, 6

有没有人知道我该怎么做?以下是可重现的数据:

mylist <- list(list(c(7, 3, 5, 4, 8), c(5, 7, 8), c(1, 5), 6), list(c(1, 
7, 3, 4, 5, 9), c(5, 9, 2, 1), c(6, 2, 4), c(6, 1), c(5, 9), 
    6))

如果你只在R中重复使用它,你可以使用saveRDSreadRDS - undefined
我在你的帖子中添加了可重现的数据。下次请使用dput函数的结果来创建可重现的数据形式。 - undefined
我对于"CSV或者更好是文本"不太清楚 - 根据你上面提到的建议格式,这两种文件类型之间唯一的真正区别就是扩展名(即文件的名称而非内容)。 - undefined
3个回答

2
这是一个例子。(ccat()并不是必需的,它只是一个帮助函数,可以节省一些打字。如果您将ccat定义为file="",则会在控制台上打印。)
ccat <- function(...,file="myfile.txt") {
   cat(...,file=file,append=TRUE)                  
}
for (i in seq_along(mylist)) {
    for (j in seq_along(mylist[[i]])) {
        ccat(i,j,mylist[[i]][[j]],sep=", ")
        ccat("\n")
    }
    ccat("\n")
}                                     

我不明白函数'ccat'的参数是什么,以及它是否必须在两个for循环之前声明。 - undefined
文件输出为空。 - undefined
1
猫的调用是否需要append=TRUE - undefined

1
考虑使用嵌套的lapply()函数来使用writeLines()。下面将内容写入文件并创建相应的newlist对象到内存中:
file <- "/path/to/myfile.txt"
conn <- file(description=file, open="w")

newlist <- lapply(seq_len(length(mylist)), function(i){

  lapply(seq_len(length(mylist[[i]])), function(j) {
      temp <- c(i, j, mylist[[i]][[j]])
      writeLines(text=paste(temp, collapse=","), con=conn, sep="\r\n")  
  })

})
close(conn)

1
写入调用是否需要 append=TRUE - undefined
对不起,@42,但是我没有收到任何错误/警告,并且文本文件已经正确生成。 - undefined

0
也许可以这样写-
mylist <- list(list(c(7, 3, 5, 4, 8), c(5, 7, 8), c(1, 5), 6),
           list(c(1, 7, 3, 4, 5, 9), c(5, 9, 2, 1), c(6, 2, 4), c(6, 1), c(5, 9), 6))

output <- NULL
count <- 1L
output <- plyr::ldply(lapply(mylist, function(x)
           {
            return(cbind(count,seq(x),plyr::ldply(x,rbind)))
            count <<- count + 1
           }))

#Then write the output as a csv file
write.csv(output, file = "output.csv")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接