在R中使用read_csv导入多个csv文件 [英] Importing multiple csv files with read_csv in r
本文介绍了在R中使用read_csv导入多个csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有多个csv文件名称的向量.
I have a vector with the names of multiple csv files.
library(readr)
data<-c("categories.csv",
"customers.csv",
"employees.csv",
"employee_territories.csv",
"order_details.csv",
"orders.csv",
"products.csv",
"regions.csv",
"shippers.csv",
"suppliers.csv",
"territories.csv")
,我想在工作区中使用 for
循环将它们全部加载.
and I would like to load all of them with a for
loop in my workspace.
我的第一次尝试是
i<-1
for (i in data) {
read_csv(data("i"))
}
也许有人可以帮助我.
推荐答案
我们可以使用 map
library(purrr)
library(readr)
out_list <- map(data, read_csv)
names(out_list) <- sub("\\.csv", "", data)
list2env(out_list, .GlobalEnv) # not recommended
或者使用 for
循环,创建一个NULL list
来存储读取数据的输出,然后循环遍历数据",读取它们并将其分配给输出列表元素
Or using a for
loop, create a NULL list
to store the output of the read data, then loop over the 'data', read them and assign it to the output list element
out_list <- vector('list', length(data))
names(out_list) <- data
for(file in data) out_list[[file]] <- read_csv(file)
如果我们要创建多个新对象(不推荐)
If we want to create multiple new objects (not recommended)
for(file in data) {
assign(sub("\\.csv", "", file), read_csv(file))
}
这篇关于在R中使用read_csv导入多个csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文