使用数据列重命名文件名 [英] rename filename with a data column

查看:35
本文介绍了使用数据列重命名文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这个问题是清楚可行的.我有许多标有简单数字 ID(例如 1.csv、2.csv、3.csv 等)的 csv 文件.另一个 csv 文件包含如下所示的实际数据

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

我的问题是如何链接数据文件中的 ID 以重命名 csv 文件.我最想要的输出是 L11a.csv、L22b.csv 等.我想我需要将每一行观察的站点、位置和块连接到另一列中,然后将该列用作 write.table 的文件名功能?

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?

我搜索了SO,这个问题很相似,只是方向相反:导入 CSV 时R如何生成带有CSV名称的列?

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!

推荐答案

我已经用四个 csv 文件和一个名为 info.txt 的文件中的数据模拟了您的场景,内容如下:

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"

(基于@joran 的评论)

(Building on @joran's comments)

这篇关于使用数据列重命名文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆