R - 将文件路径添加到数据框的每一行

R - Adding filepath to each row of a dataframe

我是 R 的新手,我正在使用同一文件夹的不同子文件夹中的许多 .csv 文件创建一个数据框。到目前为止,我得到了这个:

setwd("~/LMB/Top 6 - 2019/Juegos")

Batting.files  <- list.files(path = "~/LMB/Top 6 - 2019/Juegos/",
recursive = T, pattern=c("(statsHomeBatting.csv|statsVisitorBatting.csv)", 
                                       full.names=T))

setwd("~/LMB/Top 6 - 2019/Juegos/")

Batting.Logs <- do.call(rbind,lapply(Batting.files,read.csv, check.names = FALSE, sep = ";"))

我存放文件的子文件夹如下所示:

~\LMB\Top 6 - 2019\Juegos\Lanús at Ferro Feb 10

我想要的是在每一列中都有一个变量(让我们将其命名为 Batting.Logs$Game,它显示目录的最后一部分(在本例中为 Lanús at Ferro Feb 10

我已经搜索过旧的答案,但我无法完成它,所以我现在不确定是否可以用我现有的编码完成它。

提前致谢!

我想你想要 ?dirname()?basename()

dirname(path) returns the part of the path up to but excluding the last path separator, or "." if there is no path separator.

basename(path) removes all of the path up to and including the last path separator (if any).

示例:

一个有两条路径的dataframe,获取直接父目录,先提取目录名再提取结果的basename。

d <- data.frame(path = c('path/to/some/file.csv', 'path/to/another/file.csv'),
                stringsAsFactors = F)

d$file_dir <- basename(dirname(d$path))

d

#>                       path file_dir
#> 1    path/to/some/file.csv     some
#> 2 path/to/another/file.csv  another

如果你结合这个答案

(to the question: )

使用 dirname 和 basename(正如 npjc 已经发布的那样:),这应该可以解决问题。

Batting.files  <- list.files(path = "~/LMB/Top 6 - 2019/Juegos/",
    recursive = T, pattern=c("(statsHomeBatting.csv|statsVisitorBatting.csv)", 
                                           full.names=T))
dt.list <- sapply(file.list, fread, simplify=FALSE,data.table=F)
DT <- rbindlist(dt.list, idcol = 'folder')[, `:=` (folder = basename(dirname(folder)))]