1

我正在使用一个点数据集,其中包括来自具有唯一标识号的动物的几个 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

4

1 回答 1

0

使用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()

在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

于 2016-10-18T01:46:15.690 回答