Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...