rfor-loopif-statementwhile-looplongtable

How to make a .fhx format table?


I appreciate it if someone can help me with this problem! I have a large dataset of fire scars (data1), which I want to analyse with "burnr" package and make some graphs.

data1
year series rec_type
1926 tt_25_01 pith_year
2011 tt_25_01 bark_year
1888 tt_25_03 pith_year
1922 tt_25_03 late_fs
2011 tt_25_03 bark_year

To do so i need to make a .fhx file in r but just using as.fhx does not work because I need to add the missing years in between the pith_year and bark_year as recorder_year and I need to do that for more than 900 samples (data2).

data2
year series rec_type
1926 tt_25_01 pith_year
1927 tt_25_01 recorder_year
1928 tt_25_01 recorder_year
1929 tt_25_01 recorder_year
.
.
.
2011 tt_25_01 bark_year
1888 tt_25_03 pith_year
1888 tt_25_03 recorder_year
1888 tt_25_03 recorder_year
1888 tt_25_03 recorder_year
.
.
.
1922 tt_25_03 late_fs
2011 tt_25_03 bark_year

I really appreciate your advice and help in advance!


Solution

  • data1 <- textConnection('
      year, series, rec_type
      1926, tt_25_01, pith_year
      2011, tt_25_01, bark_year
      1888, tt_25_03, pith_year
      1922, tt_25_03, late_fs
      2011, tt_25_03, bark_year
    ') |> 
      read.csv(header = TRUE)
    
    data2 <- split(data1, data1$series) |> lapply(function(x) {
      interpolated_yrs <- seq(min(x$year) + 1, max(x$year) - 1)
      df <- data.frame(year = interpolated_yrs, 
                       series = x$series[ 1 ],
                       rec_type = 'recorder_year')
      df <- rbind(df, x)
      df
    }) |> 
      data.table::rbindlist() |> 
      as.data.frame()
    idx <- order(data2$series, data2$year)
    data2 <- data2[ idx, ]
    View(data2)