简体   繁体   中英

R: Error with gsub - removing elements in string

I have a list of file names. One of the file names is:

ABC_Earth_FullData_3-4-06.csv

I want a variable that is a substring of the filename with the date in date format only:

3-4-06

I am having trouble using gsub(). So far I've used:

file_date <- gsub(file_name = file_date, pattern = "ABC_Earth_FullData_", replacement = "", fixed = T)

And keep getting this error:

Error in gsub(file_name = file_date, pattern = "ABC_Earth_FullData_", :unused argument (file_name = file_date)

file_name is not a valid gsub argument, have a look at help

   ?gsub

try:

file_date <- gsub(x=file_name,pattern = "ABC_Earth_FullData_", replacement = "",fixed = T)

An option with str_remove

library(stringr)
str_remove_all(str1, '.*_|\\..*')
#[1] "3-4-06"

data

str1 <- 'ABC_Earth_FullData_3-4-06.csv'

You can use sub and backreference:

sub(".*_(.*)\\.csv", "\\1", str1)
[1] "3-4-06"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM