我有一个列表(414个元素),其中包含其他不同长度的列表(范围从0到9)。每个子列表具有不同数量的行和列。
一些子列表的长度为1,如下所示:
tables_list[[1]]
[,1] [,2]
[1,] "ID Number" "ABCD"
[2,] "Code" "1239463"
[3,] "Version" "1"
[4,] "Name" "ABC"
[5,] "Status" "Open"
[6,] "Currency" "USD"
[7,] "Average" "No"
[8,] "FX Rate" "2.47"
其他子列表的长度为2或更高,如下所示:
tables_list[[17]]
[[1]]
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] "" "" "USD" "Balance" "Movement in" "Aggregate" "Overall" "" "Overall"
[2,] "" "" "" "brought forward" "year" "annual" "aggregate" "" "funded account"
[3,] "" "" "" "from previous" "" "information" "adjustments" "" ""
[4,] "" "" "" "year end" "" "" "" "" ""
[5,] "" "" "" "1" "2" "3" "4" "" "5"
[6,] "12" "Value 1" "" "0" "3,275,020" "3,275,020" "" "0" "3,275,020"
[7,] "13" "Value 2" "" "0" "0" "0" "" "0" "0"
[8,] "14" "Value 3" "" "0" "8,267,862" "8,267,862" "" "0" "8,267,862"
[9,] "15" "Value 4" "" "0" "(590,073,321)" "(590,073,321)" "" "0" "(590,073,321)"
[10,] "16" "Value 5" "" "0" "0" "0" "" "0" "0"
[11,] "17" "Value 6" "" "0" "0" "0" "" "0" "0"
[12,] "18" "Value 7" "" "0" "0" "0" "" "0" "0"
[13,] "19" "Value 8" "" "0" "0" "0" "" "0" "0"
[14,] "20" "Value 9" "" "0" "(459,222,782)" "(459,222,782)" "" "0" "(459,222,782)"
[[2]]
[,1] [,2] [,3] [,4]
[1,] "Theme" "Year" "Comment" "Created"
[2,] "Line 17 Column 2" "N/A" "Amounts are calculated according to recent standards" "XXXXXXXXXXXX"
[3,] "" "" "paid by XXXXXXXXXXXXX" ""
我正在尝试将这些列表中的每一个导出到一个单独的csv文件中,但是我不知道这样做的方法。有人对如何解决这个问题有任何想法吗?我尝试使用mapply
,但始终收到以下错误:
Error in file(file, ifelse(append, "a", "w")) :
invalid 'description' argument
In addition: Warning message:
In if (file == "") file <- stdout() else if (is.character(file)) { :
Error in file(file, ifelse(append, "a", "w")) :
invalid 'description' argument
答案 0 :(得分:1)
首先是flatten the list appropriately,然后可以按常规方式对其进行循环。
flattenlist <- function(x){
morelists <- sapply(x, function(xprime) class(xprime)[1]=="list")
out <- c(x[!morelists], unlist(x[morelists], recursive=FALSE))
if (sum(morelists)) {
Recall(out)
} else {
return(out)
}
}
l <- list(a=list(1:2, b=2:4),
b=c("A", "B", "C"),
z=1,
m=matrix(4:1, 2),
d=data.frame(x=1:4, y=c(1, 3, 2, 4))
)
l.f <- flattenlist(l)
n <- paste0("robj_", names(l.f), ".csv")
sapply(1:length(l.f), function(x) write.csv(l.f[[x]], file=n[x]))