简体   繁体   English

在 R 中读取多个文件后,如何使用循环 function 重命名多个文件的名称?

[英]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.

相关问题 如何在R中的循环内重命名多个文件 - How to rename multiple files inside a loop in R 如何在R中读取具有日期名称的多个(循环).csv文件? - how to read multiple (loop) .csv files with a date name in R? R:读取多个文件并根据文件名对其进行标记 - R: Read multiple files and label them based on the file name 如何将多个xlsx文件读入R,然后将它们存储为标有xlsx文件名的单独列表? - How can I read multiple xlsx files into R and then store them as seperate lists labeled with the xlsx file name? 循环 R 以读取多个文件夹中没有名称模式的文件 - Loop in R to read Files in multiple folders with no name pattern 在 r 中循环 function 读取并保存多个数据文件 - Loop function in r to read and save multiple data files 如何从csv中读取数据帧名称并在R中的循环中使用它 - How to read data frame name from a csv and use it in a loop in R 如何使用 R 中的循环读取具有特定字符或数字的多个文件 - How to read multiple files with specific character or number using a loop in R R-如何从一个文件夹中读取多个文件,如何将它们转换为xts并对其进行一些数据分析? - R - How to read multiple files from a folder, convert them in xts and do some data analysis on them? 如何在R中的循环中命名多个pdf文件(使用不同的名称) - How to name multiple pdf files (with different names) in a loop in R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM