【问题标题】:How do I set the names of automatically imported files to be their file names in R?如何将自动导入文件的名称设置为它们在 R 中的文件名?
【发布时间】:2021-08-12 22:08:02
【问题描述】:

我正在根据包 eemR 使用以下内容导入文件文件夹:

library(data.table)
library(tidyverse)
library(eemR)

importIlliter <- function(file) {
  fluoroFrame <- fread(file) %>% as.data.frame()
  return(
    list(
      file = file,
      x = fluoroFrame[ -1, -1] %>% t() %>% as.matrix() %>% unname(),
      ex = fluoroFrame[ -1, 1] %>% as.numeric(),
      em = fluoroFrame[ 1, -1] %>% as.numeric()
    )
  )
}



folder <- file.path("C:/Users/ejs7c/OneDrive/Desktop/eemR/")

eems <- eem_read(folder, recursive = TRUE, import_function = importIlliter)

但是,当我导入文件时,它们只是简单地称为 [[1]]、[[2]].. 等等 - 有没有办法让它在我导入文件时保留它们的名称?即,一个叫做 Raman520,我希望它在作为 eem 导入时被调用(在上述代码的最后一行)。

我的最终目标是自动化 eemR 包中的一些功能,但我假设我仍然可以做到这一点,即使我让文件保留它们的名称。

谢谢

【问题讨论】:

    标签: r function import


    【解决方案1】:

    由于您已经使用tidyversefile 分配给列表名称的方法是

    names(eems) <- map_chr(eems, pluck, "file")
    

    一个演示

    library(purrr)
    
    eems <- list(
      list(file = "file_1"),
      list(file = "file_2"),
      list(file = "file_3"),
      list(file = "file_4")
    )
    
    eems
    #> [[1]]
    #> [[1]]$file
    #> [1] "file_1"
    #> 
    #> 
    #> [[2]]
    #> [[2]]$file
    #> [1] "file_2"
    #> 
    #> 
    #> [[3]]
    #> [[3]]$file
    #> [1] "file_3"
    #> 
    #> 
    #> [[4]]
    #> [[4]]$file
    #> [1] "file_4"
    
    names(eems) <- map_chr(eems, pluck, "file")
    
    eems
    #> $file_1
    #> $file_1$file
    #> [1] "file_1"
    #> 
    #> 
    #> $file_2
    #> $file_2$file
    #> [1] "file_2"
    #> 
    #> 
    #> $file_3
    #> $file_3$file
    #> [1] "file_3"
    #> 
    #> 
    #> $file_4
    #> $file_4$file
    #> [1] "file_4"
    
    eems[["file_1"]]
    #> $file
    #> [1] "file_1"
    

    reprex package (v2.0.0) 于 2021-05-24 创建

    【讨论】:

    • 谢谢 Sinh,我会在我的代码末尾添加吗?
    • 是的,将其添加到当前代码的最后。
    • 谢谢;我这样做了,但它使整个路径成为变量的名称
    • 我不理解 eems
    • 它必须是完整路径,如果不同子目录中存在同名文件会怎样?
    猜你喜欢
    • 2018-08-09
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-04
    • 2019-04-06
    • 1970-01-01
    相关资源
    最近更新 更多