使用数据列重命名文件名

使用数据列重命名文件名

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

问题描述

我希望这个问题是明确可行的.我有许多标有简单数字ID的csv文件(例如1.csv,2.csv,3.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等.我想我需要将每行观察的Site,Location和Block串联到另一列中,然后将该列用作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)

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

08-01 01:34