For a one-off, do it like this:
filepath = "W:/project/data4try1.csv""W:/project/data4try1.csv"
filename = basename(filepath)
filename_no_ext = sub(pattern = "\.[^\.]+$", replacement = "", filename)
aa <- read.csv(filepath)
aa$filename = filename_no_ext
Depending on your use case, you could turn this into a function:
read.csv.addpath = function(filepath, ...) {
filename = basename(filepath)
filename_no_ext = sub(pattern = "\.[^\.]+$", replacement = "", filename)
data <- read.csv(filepath, ...)
data$filename = filename_no_ext
return(data)
}
You might do better to use list.files
to generate a vector of all filenames and read them all at once, see How to make a list of data frames for examples of that. If you use data.table::rbindlist
or dplyr::bind_rows
on a named list of data frames, they can add the filename column for you based on the names of the list.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…