尝试使用R中名称的矢量文件重命名文件夹中的文件

时间:2019-07-18 19:17:50

标签: r

我在一个文件夹中有x个.txt文件,我想使用变量中的名称列表(向量)来重命名。

我正在尝试开发一个脚本,该脚本将重命名文件夹中的所有txt文件,并使用与脚本中原始.txt文件相对应的变量名称存储列表。我到了要在file.name()上运行sapply的地步。我相信我没有提供正确的“模式”,但我不知道要使用哪种模式。

library(dplyr)
library(stringr)

# Extract the headers of the sample table in the file.
headers <- read.csv(file="/mnt/data/Development/Sequences/SampleSheet.csv", skip = 18, header = F, nrows =1, as.is = T)

# Extract the sample rows.
sample.rows = read.csv(file="/mnt/data/Development/Sequences/SampleSheet.csv", skip = 19, header = F)

# Add the headers to the sample rows
colnames(sample.rows) = headers

# Extract the "Description" column which contains the actual names of the sample
newnames <- select(sample.rows, Description)

head(newnames)
# Define the directory where the sample files are.
startingDir<-"/mnt/data/Development/Sequences"

# identify all the samples (with ISeq-given names) in the folder.
tcr.sample <- list.files(path=startingDir, pattern="txt", full.names=TRUE )


head(tcr.sample)
# replace Iseq100 given names with Description name

sapply(tcr.sample, FUN=function(eachPath){

   file.rename(from=eachPath, to=sub(pattern="S._S.", replacement=newnames, eachPath))

})

理想情况下,我应该能够通过两位数用我存储在变量“ newnames”中的名称来更改S01_S1.txt,S02_S2.txt等的一系列文件名,例如RK_ci1151_01.txt,RK_ci1151_02等等。名称不一定遵循数字模式。我从csv列获取名称。每行具有文件的原始名称,另一行具有新名称的前缀。

0 个答案:

没有答案