Grep variable and save the result in vector to r

I have a list of txt files stored in A.path that I would like to use grep to search for the year associated with this file and store this year in vector. However, since some of these txt files have several years in the text, I would only like to keep the first year. How can i do this?

I did similar things using lapply , and here is how I started to approach this problem:

 lapply(A.path, function(i){ j <- paste0(scan(i, what = character(), comment.char='', quote=NULL), collapse = " ") year <- vector() year[i] <- grep('[0-9][0-9][0-9][0-9]', j) }) 

grep is probably not a suitable function to use, since it returns all j for every i . What function can I use here?

+5
source share
1 answer

Converting a comment into an answer, you can use gsub with \\1 to extract the value of the first match (i.e. the text matched between () in the regular expression)

 gsub(".*?([0-9]{4}).*", "\\1", j) 
+5
source

All Articles