我正在尝试将我的模型数据与r中的字段数据进行比较。字段数据位于特定深度(1,20,50,75100150..(。模型数据输出不在相同深度,必须进行插值(线性(,最好添加到字段数据的新列中。
我想对模型数据的每一行运行一个for循环,并使用近似函数对数据进行插值,以适应字段数据的深度,并将其添加到model_chla列中。我从两个数据集中提取了相同的日期(19个日期(,所以只需要对模型深度进行插值。
chla_FIELD # some of the field data with the empty model column
date depth chla model_chla
1 2008-02-21 1 0.06 NA
2 2008-02-21 20 0.05 NA
3 2008-02-21 50 0.03 NA
4 2008-02-27 1 0.08 NA
5 2008-02-27 20 0.04 NA
6 2008-02-27 50 0.03 NA
7 2008-02-27 75 0.03 NA
8 2008-02-27 100 0.01 NA
9 2008-03-07 1 0.07 NA
10 2008-03-07 20 0.05 NA
11 2008-03-07 50 0.03 NA
12 2008-03-07 75 0.02 NA
13 2008-03-07 100 0.02 NA
14 2008-03-07 150 0.01 NA
chla_MODEL # Some of the model data to be interpolated to field data depths and added to column
dt depth chla
766 2008-02-21 1.0 0.22385520
767 2008-02-21 7.5 0.21676594
768 2008-02-21 15.0 0.19189246
769 2008-02-21 25.0 0.15524526
770 2008-02-21 40.0 0.14638090
771 2008-02-21 62.5 0.14301939
772 2008-02-21 87.5 0.14094244
773 2008-02-21 112.5 0.13897014
774 2008-02-21 137.5 0.13680272
775 2008-02-21 162.5 0.13430916
776 2008-02-21 187.5 0.13133907
777 2008-02-21 212.5 0.12757768
778 2008-02-21 237.5 0.12237051
779 2008-02-21 262.5 0.11396441
780 2008-02-21 287.5 0.09206185
856 2008-02-27 1.0 0.24240938
857 2008-02-27 7.5 0.23447734
858 2008-02-27 15.0 0.21238998
859 2008-02-27 25.0 0.15545718
860 2008-02-27 40.0 0.14592259
861 2008-02-27 62.5 0.14171122
862 2008-02-27 87.5 0.13900438
863 2008-02-27 112.5 0.13662824
我的开始是这样的,但我对approx函数和在循环中向列添加数据是新手。
chla_approx <- function(FieldDATA, ModelDATA)
for (row in FieldDATA) {
}
或者有更简单的方法吗?谢谢
以下代码假设chla_FIELD
中的所有日期都存在于chla_MODEL
中。
如果数据集中的日期已经属于"Date"
类,则不需要这两条指令。
chla_FIELD$date <- as.Date(chla_FIELD$date)
chla_MODEL$dt <- as.Date(chla_MODEL$dt)
现在是split/apply/combine
。
sp_field <- split(chla_FIELD, chla_FIELD$date)
sp_model <- split(chla_MODEL, chla_MODEL$dt)
approx_fun_list <- lapply(sp_model, function(data){
approxfun(data[["depth"]], data[["chla"]])
})
chla_FIELD <- lapply(names(sp_field), function(nm){
f <- approx_fun_list[[nm]]
sp_field[[nm]]$model_chla <- f(sp_field[[nm]]$depth)
sp_field[[nm]]
})
chla_FIELD <- do.call(rbind, chla_FIELD)
最终清理。
rm(sp_field, sp_model)
谢谢瑞。为了统计的目的,如果我加上一个";源";列到两个数据集:
date depth chla source
1 2008-02-21 1 0.06 FIELD
2 2008-02-21 20 0.05 FIELD
3 2008-02-21 50 0.03 FIELD
dt depth chla source
766 2008-02-21 1.0 0.22385520 MODEL
767 2008-02-21 7.5 0.21676594 MODEL
768 2008-02-21 15.0 0.19189246 MODEL
769 2008-02-21 25.0 0.15524526 MODEL
770 2008-02-21 40.0 0.14638090 MODEL
771 2008-02-21 62.5 0.14301939 MODEL
如何在split函数之后将数据按序列组合?(仍然对模型chla进行插值以匹配景深(要得到这样的东西:
1 2008-02-21 1 0.06 FIELD
2 2008-02-21 20 0.05 FIELD
3 2008-02-21 50 0.03 FIELD
1 2008-02-21 1 0.06 MODEL
2 2008-02-21 20 0.05 MODEL
3 2008-02-21 50 0.03 MODEL
4 2008-02-27 1 0.08 FIELD
5 2008-02-27 20 0.04 FIELD
6 2008-02-27 50 0.03 FIELD
4 2008-02-27 1 0.08 MODEL
5 2008-02-27 20 0.04 MODEL
6 2008-02-27 50 0.03 MODEL