2017-09-24 73 views
0

我需要通過引用包含兩個相應列中的舊名稱和所需新名稱的15000行Excel表來重命名15000個PDF。嘗試重命名PDF時使用excel作爲參考時出現錯誤R

我的Excel工作表看起來是這樣的: Reference Excel

我保持一個文件夾,名爲在我的文件 - SDP迴應。然後運行以下腳本:

#Use Readxl and dplyr package 
library(readxl) 
library(dplyr) 

#Set Working Directory as Desktop 
setwd("/Users/shwetachopra/Desktop") 

#Set path to folder that contains our PDFs as Folder 
folder <- "/Users/shwetachopra/Desktop/SDP Responses" 

#Create vector of list of PDF names, from folder 
oldnames <- as.vector(list.files(folder)) 

#Export excel of matching newnames in same order as above 
sdpdata <- read_excel("NewSDPNames.xlsx") 

#Change working directory to folder containing the pdfs 
setwd("/Users/shwetachopra/Desktop/SDP Responses") 

#Separately extract the column which contain the matching old names 
oldies <- sdpdata[[2]] 

#filter rows that match old file names 
subset <- sdpdata[grep(paste(oldnames, collapse="|"),oldies),] 

#extract new file names 
new_names <- subset[[3]] 

#rename old file names with new ones 
file.rename(oldnames,new_names) 

的腳本工作,當我在100個PDF文件運行它,完美的重命名它們。但是,只要我再添加一個文件(在101處),就會將它們重新命名爲不準確,從而將舊名稱與不正確的新名稱進行匹配。我的腳本中沒有設置任何限制,並且無法理解爲什麼它會創建超過100個PDF的不準確內容。

我是R新手,不得不通過谷歌來了解這一點。我非常感謝一些幫助,以確保我可以將所有15000個PDF文件重新命名。

+0

請查看[editing-help](http://stackoverflow.com/editing-help)。 – Cyrus

回答

0

試試這個:

library(readxl) 

#Set Working Directory as Desktop 
setwd("/Users/shwetachopra/Desktop/SDP Responses") 

#Read the list of PDFs 
oldnames = list.files(".", pattern = ".pdf$") 

# Read the excel with 'Old PDF Names' and 'New Names' columns 
sdpdata <- read_excel("NewSDPNames.xlsx") 

# Only select from sdpdata those files that are in oldnames 
subset = sdpdata $`Old PDF Names` %in% oldnames 

# Rename 
file.rename(from = sdpdata $`Old PDF Names`[subset], 
      to = sdpdata $`New Names`[subset]) 

我認爲你的問題可能是由於到最後一行

file.rename(oldnames,new_names) 

比較的oldnames的長度,以new_names。如果它們不匹配,那麼在excel中可能沒有該文件夾中的一個或多個文件的條目。

相關問題