Insert part of file name as column value

I ran a loop which goes over many folders to convert TIF file to a data frame, but I want to insert part of the file name as a column value. Is it possible?.
For example, if my file name is "Rain_02_02_2010_southRegion", I want to take only "2010" and make it as a value in a new column. The second file might have "Rain_02_02_2017_southRegion", so I want to take 2017 and so on. I tried dat["Date"] <-, but I couldn't insert the code that makes it work.

ls = list.files()
for(i in ls){
  rs=list.files(paste0(getwd(),"/",i),pattern=".tif$",full.names=T)
  rs = lapply(rs,raster)
  rs=do.call(stack,rs)
  dat=as.data.frame(rs, xy =TRUE)
  dat= dat[complete.cases(dat), ]
  dat["Date"] <- 
}

Here is an example that relies on the fact that the text you want to extract from the file name is the first occurrence of four consecutive digits.

library(stringr)
df <- data.frame(x = 1:4, y = 11:14)
df
#>   x  y
#> 1 1 11
#> 2 2 12
#> 3 3 13
#> 4 4 14
DummyName <- "Rain_02_02_2010_southRegion"
YR <- str_extract(DummyName, "\\d{4}")
df["DATE"] <- YR
df
#>   x  y DATE
#> 1 1 11 2010
#> 2 2 12 2010
#> 3 3 13 2010
#> 4 4 14 2010

Created on 2019-06-23 by the reprex package (v0.2.1)

Or you can use Base R:

YR <- substr(DummyName, 1, 4)

It worked perfectly. I really appreciate it.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.