Home > OS >  Adding a column to a list of dataframe with lapply
Adding a column to a list of dataframe with lapply

Time:02-19

I have a large panel data with provinces for each year-month. I would like to run a function through a list of data frames (that I create based on this initial data frame) in order to get a new column for each of them with the input of this function. However, when I run the code, the new column does not appear. Here is the code:

> head(dataSPEI)
# A tibble: 6 x 11
  adm1    year month prov_code mean_temperaturec neighboors   province_name avgpreci longitude latitude   PET
  <chr>  <dbl> <dbl> <chr>                 <dbl> <chr>        <chr>            <dbl>     <dbl>    <dbl> <dbl>
1 TUR034  1978     1 TR100                  5.61 TR100, TR21~ Istanbul        170.        28.8     41.2     0
2 TUR034  1978     2 TR100                  7.48 TR100, TR21~ Istanbul         88         28.8     41.2     0
3 TUR034  1978     3 TR100                  8.55 TR100, TR21~ Istanbul         71         28.8     41.2     0
4 TUR034  1978     4 TR100                 11.6  TR100, TR21~ Istanbul         88.7       28.8     41.2     0
5 TUR034  1978     5 TR100                 16.6  TR100, TR21~ Istanbul         33.2       28.8     41.2     0
6 TUR034  1978     6 TR100                 20.8  TR100, TR21~ Istanbul          5.30      28.8     41.2     0

dat.s <- split(dataSPEI, dataSPEI$prov_code)

lapply(dat.s, function(x) {
  x$PET <- thornthwaite(x$mean_temperaturec, x$latitude[1])
  return(x)
  })

Does someone know what I am doing wrong?

CodePudding user response:

Try assigning the result of the lapply call to an object; in this case, you can assign back to the originating list of dataframes

dat.s<-lapply(...)

  • Related