如何使样条函数在嵌套列表上工作

How to make the spline function work on a nested lists

我正在尝试将嵌套列表传递给样条函数。我有两个城市连续两年的季度降雨量值。我正在尝试执行样条插值,以便我可以取回那些年的月度值

这是我尝试过的:

# Create a dummy data-frame
df = data.frame(city_name = rep(sapply(c('city_a','city_b'), function(x) {rep(x, 8)}), 1),
                period = rep(sapply(c('2016-17','2017-18'), function(x) {rep(x, 4)}), 2),
                quarter = rep(sapply(c('q1','q2','q3','q4'), function(x) {rep(x, 1)}), 4),
                e_date = rep(seq(zoo::as.Date('2016-12-01'),zoo::as.Date('2018-09-01'), by='quarter'),2),
                x = c(5.3, 5.7, 5.6, 5.9, 5.8, 6.1, 6.2, 6.5, 5.7, 5.8, 5.5, 5.9, 5.7, 5.8, 6.1, 6.1))
# Create separate lists for each city
out <- split(df, f = df$city_name)
# Columns to exclude from the lists - way spline works I guess!
cols_to_drop = c('city_name','period','quarter')
# drop desired cols from each list
temp <- lapply(out, function(x) x[,!(colnames(x) %in% cols_to_drop), drop=F])
# create a sequential placeholder for monthly dates
monthly = sort(seq(zoo::as.Date('2016-12-01'), zoo::as.Date('2018-09-01'), by="month"))
# Create lists using spline interpolation
spline_df <- data.frame(periodicity=monthly, x_est=spline(temp$city_a, method = 'fmm', xout = monthly)$y)

但是我怎样才能传递整个列表而不是传递 temp$city_name 以便它 returns 一个由内插列表或数据框组成的数据框?

城市名称可以是列索引或行索引 - 都可以

再用一个lapply:

lapply(temp, function(x) data.frame(periodicity = monthly, 
                                    x_est = spline(x, method = "fmm", xout = monthly)$y))

$`city_a`
   periodicity    x_est
1   2016-12-01 5.300000
2   2017-01-01 5.561970
3   2017-02-01 5.682823
4   2017-03-01 5.700000
5   2017-04-01 5.654594
6   2017-05-01 5.601360
7   2017-06-01 5.600000
8   2017-07-01 5.688729
9   2017-08-01 5.817018
10  2017-09-01 5.900000
11  2017-10-01 5.884073
12  2017-11-01 5.822975
13  2017-12-01 5.800000
14  2018-01-01 5.871115
15  2018-02-01 5.996324
16  2018-03-01 6.100000
17  2018-04-01 6.159644
18  2018-05-01 6.180863
19  2018-06-01 6.200000
20  2018-07-01 6.246211
21  2018-08-01 6.341269
22  2018-09-01 6.500000

$city_b
   periodicity    x_est
1   2016-12-01 5.700000
2   2017-01-01 5.863398
3   2017-02-01 5.878445
4   2017-03-01 5.800000
5   2017-04-01 5.657224
6   2017-05-01 5.533108
7   2017-06-01 5.500000
8   2017-07-01 5.606924
9   2017-08-01 5.779904
10  2017-09-01 5.900000
11  2017-10-01 5.886253
12  2017-11-01 5.789890
13  2017-12-01 5.700000
14  2018-01-01 5.678300
15  2018-02-01 5.722906
16  2018-03-01 5.800000
17  2018-04-01 5.904787
18  2018-05-01 6.008343
19  2018-06-01 6.100000
20  2018-07-01 6.156842
21  2018-08-01 6.164108
22  2018-09-01 6.100000