如何在 R 中创建简单的自定义函数

问题描述 投票:0回答:0

我有一个树木生长数据库,其中包含每棵树和每年(在本例中:每年 2 棵不同的树,2 年)的每个 DOY(一年中的一天)处于“扩大”生长阶段的细胞数。如您所见,我每隔几周就会去实地采集样本。数据库看起来像这样(简化):

df <- data.frame("Year" = c(2012, 2012, 2012, 2012, 2012, 2012,2012,
                            2012, 2012, 2012, 2013, 2013, 2013,
                            2013, 2013, 2013, 2013, 2013, 2013, 2013),
  "Tree" = c(15, 15, 15, 15, 15, 22, 22, 22, 22, 22, 41, 41,
             41, 41, 41, 53, 53, 53, 53, 53),
  "DOY" = c(65, 97, 125, 177, 214, 65, 97, 125, 177, 214,
            61, 99, 118, 166, 221, 61, 99, 118, 166, 221),
  "Enlarging" = c(0, 2, 4, 5, 2, 1, 3, 6, 3, 1, 0, 3, 4, 3, 1, 2, 4, 7, 5, 2))


df <- df %>%
  mutate(Year = as.factor(Year),
         Tree = as.factor(Tree),
         DOY = as.numeric(DOY),
         Enlarging = as.numeric(Enlarging))


print(df)
   Year Tree DOY Enlarging
1  2012   15  65         0
2  2012   15  97         2
3  2012   15 125         4
4  2012   15 177         5
5  2012   15 214         2
6  2012   22  65         1
7  2012   22  97         3
8  2012   22 125         6
9  2012   22 177         3
10 2012   22 214         1
11 2013   41  61         0
12 2013   41  99         3
13 2013   41 118         4
14 2013   41 166         3
15 2013   41 221         1
16 2013   53  61         2
17 2013   53  99         4
18 2013   53 118         7
19 2013   53 166         5
20 2013   53 221         2

我想应用一个GAM函数来了解扩大增长阶段的增长曲线。 应用 GAM 后,我想获得 DAILY 预测(从采样的第一天到最后一天)关于每年每棵树的生长阶段何时开始和结束。为此,我想创建一个简单的函数(在本例中称为

gamfun
),它应用模型和对每棵树的预测并返回拟合:

gamfun <- function(Year, Tree){
  
#create the gam model

  enlarging_model <- gam(Enlarging ~ s(DOY), data = df, quasipoisson, gamma = 1, min.sp = 1)
  
  new_DOY <- seq(min(datosSTD$DOY), max(datosSTD$DOY), 1) #create daily sequence for day of the year

#predict daily growth base on the previous model
  
  enlarging_pred <- as.vector(predict(enlarging_model, data.frame(new_DOY), type="response"))
  
  fit <- data.frame(cbind(DOY=DOY, enlarging_pred = enlarging_pred))
  return(fit)
}

#Apply this model and predictions for every tree of every year

Table <- (as.data.frame(mapply(gamfun, Year=df$Year,Tree=df$Tree,
                                 SIMPLIFY = TRUE, USE.NAMES=TRUE)))

基本上我想得到一年中每一天的细胞数量的预测值(拟合),但我最终得到错误,我想是因为我的语法不好,但我真的不知道怎么写正确。在这一点上,我得到一个包含数千列(称为 V1、V2...V1260)的数据帧作为输出,每列有 2 行(DOY 和扩大)。在预测行中,值似乎每一列都在重复。像这样的东西:

                     V1                          V2
DOY            c(59, 60, 61,  [...]          c(59, 60, 61,  [...]
enlarging_pred c(0.0337, 0.0363, [...]       c(0.0337, 0.0363, [...]

我想我的语法错误可能在最后,当试图获得表输出时。我的真实数据库更复杂,6 棵树而不是 2 棵树,10 年而不是 2 年,4 个生长阶段而不是 1 个。所以我真的需要一种有效的方法来应用 gam 模型并获得该数量树木的每日预测和岁月。

希望有人能帮助我,我真的被困住了。非常感谢你。

r dplyr predict gam custom-function
© www.soinside.com 2019 - 2024. All rights reserved.