尝试在 R 中生成和存储多个 KDE 模型

Trying to generate and store multiple KDE models in R

我正在处理一个点数据集,其中包含来自具有唯一标识号的动物的多个 gps 项圈的数据。

我想做的是使用每只动物的核密度估计器为它们的范围建模。我已经生成了每个模型的图表,但我需要为每个模型保存实际估算器以供进一步分析。我要在这里揭露我的无知,但我试图用 for 循环来做到这一点。

collars<-unique(gps$CollarID)

gps 是我的数据框

for (i in 1:length(collars)){
    collar<-subset(gps, CollarID == collars[i], select=c(Easting, Northing))
    cxy<-cbind(collar$Easting,collar$Northing)
    kde<-kde(cxy)
    plot(kde, xlab = "X", ylab = "Y")
    title(main = collars[i])
}

我所追求的是为每次迭代生成一个唯一命名的 kde 对象。我曾尝试将计数器包含在对象的名称中,但很快发现那行不通。

如有任何帮助,我们将不胜感激!

-JF

使用dplyr,您可以将计算包装在一个函数中,为每个计算 kde 东向、北向观察并将生成的 kde 对象保存在列表中,由单独的函数绘制

由于我们没有样本数据集,所以我使用了 mtcars 数据集。

#load libraries, assuming you are using kde function from "ks" library
library("dplyr")
library("lazyeval") #required for interp function
library("ks")



DF = mtcars
indexColName = "cyl"
indexVar = unique(DF[,indexColName])
calcVars = c("hp","wt")


### Replacement values for your dataset ###

# DF = gps
# indexColName = "CollarID"
# indexVar = unique(DF[,indexColName])
# calcVars = c("Easting","Northing")

kde 计算函数:

fn_kdeCalc <- function(indexVarInput = indexVar,indexColInput = indexColName,calcVarsInput=calcVars) {

cat("Begin kde calc for",indexColInput,"=",indexVarInput,"\n")

#filter condition logic translates as CollarID == collars[i]
#the following is required for dynamic inputs , you can read more from trying, vignette("nse")

filter_criteria <- interp(~ filter_column == indexVarInput, filter_column = as.name(indexColInput))

kdeObj <- DF %>% 
        dplyr::filter_(filter_criteria) %>%           # subset dataset to specific filter condition
        dplyr::select(one_of(calcVarsInput)) %>%      # select specific columns for kde calc
        kde()                                         # calculate kde for selected variables

cat("End kde calc for",indexColInput,"=",indexVarInput,"\n")

return(kdeObj)

}

#calculate kde for each unique input variable using above function and save in a list

kdeObjList = lapply(indexVar,function(x) { 

fn_kdeCalc(indexVarInput = x,indexColInput = indexColName,calcVarsInput=calcVars) 

})

kde 绘图函数:

fn_kdePlot = function(kdeObject = NULL,titleObj = NULL,labelVars=calcVars) {
  plot(kdeObject, xlab = labelVars[1], ylab = labelVars[2],main = paste0("Kernel Density estimation for ",indexColName,":",titleObj) )
}



### save plots ###
# you can use png() to save in different file for each plot or 
# pdf("KDE_plots1.pdf") to include them in one file

png()

lapply(1:length(kdeObjList), function(x) fn_kdePlot(kdeObject = kdeObjList[[x]],titleObj = indexVar[x]) )

dev.off()