[英]How to use loop function to rename multiple files' name after read them in R?
I have multiple files under the folder of "rawdata", after read them and assigned them as seperated dataset, i also want to rename them from "dataset 1 a.csv" to "dataset1".我在“rawdata”文件夹下有多个文件,在读取它们并将它们分配为单独的数据集后,我还想将它们从“dataset 1 a.csv”重命名为“dataset1”。
I wrote the code that achieve the first goal,using the first loop read all files as a list, then use the second loop to unset the list: ldf.我编写了实现第一个目标的代码,使用第一个循环将所有文件作为列表读取,然后使用第二个循环取消设置列表:ldf。 But I don't know where I should add the code to let R change all file's name at once?
但我不知道我应该在哪里添加代码让 R 一次更改所有文件的名称? I tried to add str_replace_all (names(ldf)," ", "-") at different places, but all returned wrong outputs, and it cannot solve the issue of getting rid of ".csv".
我尝试在不同的地方添加 str_replace_all (names(ldf)," ", "-") ,但都返回错误的输出,并且无法解决摆脱“.csv”的问题。 Thanks a lot~~
非常感谢~~
Here is my code:这是我的代码:
datanames<-list.files(here("rawdata"))
ldf<-list()
for (i in (datanames)){
ldf[[i]]<-import(here("rawdata",i))
for (j in names(ldf)){
assign(j,ldf[[j]], .GlobalEnv)
}
}
I'm not sure the pattern of the name you want to replace, but if it is blank-number-blank-letter.csv, use gsub to remove.我不确定您要替换的名称的模式,但如果它是空白数字空白字母.csv,请使用 gsub 删除。
I'm not sure how you will import,but can use read.csv我不确定你将如何导入,但可以使用 read.csv
Assign will assign the name.分配将分配名称。
lapply(1:length(list.files()), function(i) assign(gsub(" [0-9] [a-z].csv", "", list.files()[i]), read.csv(list.files()[i])))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.