rename filename with a data column

假装没事ソ 提交于 2019-12-11 20:19:19

问题


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!


回答1:


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)




回答2:


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")))


来源:https://stackoverflow.com/questions/20591010/rename-filename-with-a-data-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!