首页 > 解决方案 > Changing the name of a dataframe inside of a dataframe

问题描述

I am working with a folder of csv files. These files were imported using the following code:


data_frame <- list.files("path", pattern = ".csv", all.files = TRUE, full.names = TRUE)

csv_data <- lapply(data_frame, read.csv)

names(csv_data) <- gsub(".csv","", 
                        list.files("path", pattern = ".csv", all.files = TRUE, full.names = FALSE),
                        fixed = TRUE)

After this has been generated the dataframes hold the name of the csv. Since I have over 3000 csv files, I was wondering how to change the name of them to keep track of them better.

For example, instead of 'City, State, US', it will generate 'City-State-US'.

I apologize if this has already been asked, but I cannot find anything that could help.

标签: rdataframecsv

解决方案


因此,如果我正确理解您的问题,您的 CSV 文件名称为“City、State、US.csv”(即“Chicago、IL、USA.csv”等),您正在将它们读入 R 并将它们存储在列表元素名称为 CSV 名称的列表,并且您想对该元素名称进行一些更改?

您可以使用 访问列表项的名称names(csv_data),就像您在上面所做的那样,然后按您喜欢的方式处理它并将其写回相同的名称。

例如,您给出的示例:

names(csv_data) <- gsub(", ", "-", names(csv_data), fixed = TRUE)

这应该做你需要的。如果您需要做其他事情,只需将 gsub 参数或函数更改为其他内容 - 关键是您可以一次性提取并写回列表项名称。

您已经在第三行中执行此操作,您可以在其中命名项目 - 您甚至可以在分配名称之前进行处理。

编辑:另外,快速说明:您已经将 list.files 的输出存储在 data_frame 变量中 - 您可以在第三行中重用该变量,而不是再次调用 list.files 。


推荐阅读