r - R脚本打开文件夹,然后识别文件,重命名并读取它
问题描述
我最近学会了使用 R 进行编码,并且我设法处理文件中的数据,但我无法让它自己操作文件。这是我的问题:
我想在我的工作目录中依次打开"Laurent/R"
其中的 3 个文件夹("gene_1"
、"gene_2"
、"gene_3"
)。
在每个文件夹中,我希望将一个特定的 .csv 文件(包含特定单词“Cq”的文件)重命名为“gene_x_Cq”(然后将这 3 个重命名的文件移动到新文件夹中(有必要吗?))。
然后我希望能够连续打开这 3 个 .csv 文件(我想是 read.csv)来操作其中的数据。我查看了不同的功能,例如list.file
, unlist
,file.rename
但我确信它们是合适的,我不知道如何在我的情况下使用它们。任何人都可以帮忙吗?(我用的是 Mac)谢谢 Laurent
解决方案
这是一个潜在的解决方案。如果您有不明白的地方,请大声问出来!
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)
推荐阅读
- makefile - 如何使用 Visual Studio 编译生成文件
- c - 我不知道如何输出文件和创建附加程序
- sql-server - 使用两个变量更新列
- flutter - 如何在 FLutter 中提取 xz 文件?
- .net - 如果用户将几个参数留空并想省略,如何将参数传递给方法?
- c - 用于在宏扩展期间跟踪 C 预处理器执行的工具?
- javascript - 一旦 ref.current 发生变化,更新组件
- tarantool - 问:如何在引导的 Tarantool Cartridge 集群中更改 cluster_cookie?
- java - 使用 mockito 存根 void 方法不起作用
- objective-c - 注入然后使用方法