0

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!

Community
  • 1
  • 1
  • You don't need `write.table` at all. Play around with `list.files` and `file.rename`. That, plus a for loop and `paste` should be all you need. – joran Dec 15 '13 at 04:07
  • ...in fact, it appears that `file.rename` is vectorized, so you probably don't even need the for loop. This could probably be squeezed into as few as 2-3 lines of code. – joran Dec 15 '13 at 04:08

2 Answers2

2

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)

vaettchen
  • 7,299
  • 22
  • 41
  • Thank you for interpreting joran's comments. I am not sure how to write a for loop and use the paste(). Your code worked as my example indicated, but my actual situation is a little bit more complicated. I have IDs that do not have a corresponding csv files and I have replicate csv files without a corresponding separate ID (e.g., 1.csv and 1r.csv but only one row of observation for ID 1 in data file). How would this code be modified to work? – user2770184 Dec 15 '13 at 23:26
  • I don't understand the "but only one row of observation for ID 1 in data file" part. Can you edit your original question so that it reflects the real problem? – vaettchen Dec 19 '13 at 11:00
1

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")))
datawookie
  • 1,607
  • 12
  • 20