如何在将多个csvs读入R时将文件名转换为变量 [英] How can I turn the filename into a variable when reading multiple csvs into R

查看:256
本文介绍了如何在将多个csvs读入R时将文件名转换为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆csv文件遵循命名方案:est2009US.csv。

I have a bunch of csv files that follow the naming scheme: est2009US.csv.

我正在读它们到R中,如下:

I am reading them into R as follows:

myFiles <- list.files(path="~/Downloads/gtrends/", pattern = "^est[[:digit:]][[:digit:]][[:digit:]][[:digit:]]US*\\.csv$")

myDB <- do.call("rbind", lapply(myFiles, read.csv, header = TRUE))

我想找到一种方法来创建一个新变量,为每个记录填充文件的名称记录来自。

I would like to find a way to create a new variable that, for each record, is populated with the name of the file the record came from.

推荐答案

您可以先从 lapply 创建对象。

Lapply <- lapply(myFiles, read.csv, header=TRUE))
names(Lapply) <- myFiles
for(i in myFiles) 
    Lapply[[i]]$Source = i
do.call(rbind, Lapply)

这篇关于如何在将多个csvs读入R时将文件名转换为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆