Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

How to put file name into a field using R

I use the code aa <- read.csv("W:/project/data4try1.csv") to read a file into aa data frame. I want to create a new field (say: filename) in aa to hold the file name "data4try1" (exclude ".csv") for each rows. it looks like:

filename, var1, var2
data4try1,123,456
data4try1,001,abc
data4try1,bc,786
question from:https://stackoverflow.com/questions/66049356/how-to-put-file-name-into-a-field-using-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...