【问题标题】:Is there a possibility to export data.frames stored insides two lists in R?是否有可能导出存储在 R 中两个列表中的 data.frames?
【发布时间】:2021-01-21 11:48:15
【问题描述】:

我又遇到了一个列表问题。 我有七个不同的数据框存储在一个列表中。其中六个列表一起存储在另一个列表中。 (听起来很复杂,我知道 :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_list 之一的命令,它会起作用。你知道如何解决这个问题吗?我希望这是可以理解的。如果没有,我可以尝试上传支持我描述的图片吗?

寻找你有用的想法:) 凯瑟琳

【问题讨论】:

    标签: r list for-loop


    【解决方案1】:

    您可以使用tidyverse 包尝试以下代码。每个较低列表的数据将保存到它们各自的目录中,我将其命名为 d1d4

    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))
    
    
    
    
    
    

    【讨论】:

      猜你喜欢
      • 2021-03-21
      • 2021-03-08
      • 2013-01-24
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 2022-01-10
      • 2019-09-29
      相关资源
      最近更新 更多