【问题标题】:R script to open folders then identify a file, rename it, and read itR脚本打开文件夹,然后识别文件,重命名并读取它
【发布时间】:2020-08-05 13:33:55
【问题描述】:

我最近学会了使用 R 进行编码,并且我设法处理了文件中的数据,但我无法让它自己操作文件。这是我的问题:

我想在我的工作目录"Laurent/R" 中依次打开其中的 3 个文件夹("gene_1""gene_2""gene_3")。

在每个文件夹中,我希望将一个特定的 .csv 文件(包含特定单词“Cq”的文件)重命名为“gene_x_Cq”(然后将这 3 个重命名的文件移动到新文件夹中(有必要吗? ))。

然后我希望能够连续打开这 3 个 .csv 文件(我想是 read.csv)来操作其中的数据。 我查看了不同的功能,例如list.fileunlistfile.rename,但我确信它们是合适的,我不知道如何在我的情况下使用它们。 任何人都可以帮忙吗? (我用的是 Mac) 谢谢 洛朗

【问题讨论】:

  • 嗨劳伦特!您的“gene_1”、“gene_2”等文件夹中是否还有其他包含“Cq”字样的文件?这将帮助人们为您量身定制答案。
  • 查看file.choosefile.renamelist.files

标签: r rename


【解决方案1】:

这是一个潜在的解决方案。如果你有什么不明白的地方,就大声问吧!

setwd("Your own file path/Laurent")
library(stringr)

# list all .csv files
csvfiles <- list.files(recursive = T, pattern = "\\.csv")
csvfiles

# Pick out files that have cq in them, ensuring that you ignore uppercase/lowercase
cq.files <- csvfiles[str_detect(csvfiles, fixed("cq", ignore_case = T))]

# Get gene number for both files - using "2" here because gene folder is at the second level in the file path
gene.nb <- str_sub(word(cq.files, 2, 2, sep = "/"), 6, 6)
gene.nb

# create a new folder to place new files into
dir.create("R/genefiles")

# This will copy files, not move them. To move them, use file.rename - but be careful, I'd try file.copy first.
cq.files <- file.copy(cq.files,
                        paste0("R/genefiles/gene_", gene.nb, "_", "Cq", ".csv"))

# Now to work with all files in the new folder
library(purrr)
genefiles <- list.files("R/genefiles", full.names = T)

# This will bring in all data into one dataframe. If you want them brought in as separate dataframes,
# use something like gene1 <- read.csv("R/genefiles/gene_1_Cq.csv")
files <- map_dfr(genefiles, read.csv)

【讨论】:

  • 非常感谢 Nova,它确实帮助了我!!
  • 洛朗太棒了!如果您喜欢我的回答,您可以“投票”它(请参阅我的回答旁边的箭头,左上角)。您还可以“接受”我的回答(在投票区域下方打勾),以便其他用户在搜索类似内容时知道您的问题已得到回答。投票和接受答案可以帮助像我这样的用户增加声望点,这些点以后可以用来为我们自己的问题提供“赏金”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-07
  • 2014-12-27
  • 1970-01-01
  • 1970-01-01
  • 2013-11-24
  • 2020-10-28
相关资源
最近更新 更多