[英]Is there a possibility to export data.frames stored insides two lists in R?
我又遇到了列表問題。 我有七個不同的數據框存儲在一個列表中。 其中六個列表一起存儲在另一個列表中。 (聽起來很復雜,我知道: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
package 嘗試以下代碼。 每個較低列表的數據將保存到我將其命名為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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.