rename filename with a data column

2019-09-02 13:28发布

I hope this question is clear and feasible. I have many csv files labelled with a simple numeric ID (e.g., 1.csv, 2.csv, 3.csv, etc.). Another csv file contains the actual data like below

ID  Site  Location Block  
1    L1     1         a
2    L2     2         b
3 etc

My question is how to link the ID in the data file to rename the csv files. The output I would ideally like to have is L11a.csv, L22b.csv, etc. I think I need to concatenate each row observation's Site, Location, and Block into another column and then use that column as the filename for the write.table function?

I searched SO and this question is similar except in the reverse direction: When importing CSV into R how to generate column with name of the CSV?

Many thanks for your assistance. This would save me hours in renaming files!

2条回答
ら.Afraid
2楼-- · 2019-09-02 13:33

I have simulated your scenario with four csv files and the data in a file called info.txt with this content:

"ID","Site","Location","Block"
1,"L1",1,"a"
2,"L2",2,"b"
3,"L3",3,"c"
4,"L4",4,"d"

For this setup the following code will achieve what you want if my understanding is correct:

x <- list.files( pattern = ".csv" )
info <- read.table( file = "info.txt", sep = ",", header = TRUE, 
                    row.names = FALSE, stringsAsFactors = FALSE )
y <- paste( info[ ,"Block" ], ".csv", sep = "" )
for( i in c( "Location", "Site" ) ) y <- paste( info[ ,i ], y, sep = "" )
file.rename( x, y )

list.files( pattern = ".csv" )
[1] "L11a.csv" "L22b.csv" "L33c.csv" "L44d.csv"

(Building on @joran's comments)

查看更多
时光不老,我们不散
3楼-- · 2019-09-02 13:39

Here's another option:

info <- read.table( file = "info.txt", sep = ",", header = TRUE, row.names = NULL,
    stringsAsFactors = FALSE )

with(info, file.rename(paste0(ID, ".csv"), paste0(Site, Location, Block, ".csv")))
查看更多
登录 后发表回答