我又有一个列表问题。我有七个不同的数据帧存储在一个列表中。这些列表中的6个一起存储在另一个列表中。(听起来很复杂,我知道:D)
如此,如。数据(mtcars)
df1 <- tail(mtcars)
df2 <- mtcars[1:5, 2:10]
df3 <- mtcars
df4 <- head(mtcars)
lower_list1 <- list(df1, df2, df3, df4)
然后我有5个其他的lower_lists (lower_list2, lower_list3, lower_list4)存储在列表中的:upper_list
upper_list <- list(lower_list1, lower_list2, lower_list3, lower_list4)
,现在我想导出所有这些数据帧在自己的目录,我之前创建了一个RegEx的帮助:
files <- str_extract(names(upper_list), pattern = "^([a-z])(_)([a-z])([1-9])")
for(i in 1:length(files)) {
dir.create(paste0("./Exports/Taxa-Tables/", files[i]))
}
目前为止我尝试的是:
for (f in upper_list) { # f are the lists inside the upper list
lapply(seq_along(f),
function(i) write.table(f[[i]],
paste0("./parent/", str_extract(names(upper_list)[i],
pattern = "^([a-z])(_)([a-z])([1-9])")]),
row.names = FALSE, sep = "t"))
}
我认为问题在这里:
str_extract(names(upper_list)[i]
# I am not sure if it is names(upper_list)[[i]] or names(upper_list[[f]], both times I get the error. With the example outside the loop it works, there I wrote
`names(upper_list)[[1]]` #' to get the first list of the upper_list
Maybe one could include a command to get the index of the list?
我得到的错误是:
Error in file(file, ifelse(append, "a", "w")) :
cannot open the connection
In addition: Warning message:
In file(file, ifelse(append, "a", "w")) :
cannot open file './parent/lower_list1/': Permission denied
如果我在循环外尝试命令获取其中一个lower_lists,它可以工作。你知道如何解决这个问题吗?我希望你能理解。如果没有,我可以上传支持我描述的图片。
寻找你有用的想法:)凯瑟琳
您可以使用tidyverse
包尝试下面的代码。每个下链表的数据将保存到它们各自的目录中,我将其命名为d1
到d4
。
library(tidyverse)
df <- tibble(upper = upper_list, dir_name = paste0("d", 1:4),
file_name = list(paste0("file_", 1:4, ".csv"))) %>%
mutate(dir_vec = map(dir_name, ~rep(.x, 4)),
path = map2(dir_vec, file_name, ~file.path(.x, .y)))
# create the 4 directories
walk(df$dir_name, dir.create)
# save the data stored in list into their directory
map2(df$upper, df$path, ~walk2(.x, .y, write.csv))