rattributesshapefiler-sfspatial-data

R Programming Help: Error in .subset2(x, i, exact = exact) : no such index at level 3


I am in need of assistance, any guidance is greatly appreciated!

My goal is to create a function that computes the spatial moving average of adjacent neighbors of a polygon shapefile utilizing the existing function poly2nb(). The function must be flexible so that it may call upon any attribute within the working shapefile. I am not sure how to fix the error I am receiving: Error in .subset2(x, i, exact = exact) : no such index at level 3, when I attempt to call my function. I am at a complete loss as to how to fix this issue.

I am working with a shapefile of Chicago neighborhood data, mulypolygon, containing the attributes:

•Community Area ID
•Community Name
•Tract Cnt
•Pop2014
•Hisp14P
•PerCInc14
•Assault
•DiabetM
•FirearmM
•LungCancer

My Function A

a_spmvavg <- function(shapefile, my_attribute) {
    nbs = poly2nb(shapefile)
    a_matrix = nb2mat(nbs, style='W', zero.policy=TRUE)
    a_val = shapefile[[my_attribute]]
    a_average1 = a_matrix%*%a_val
    a_newdf = cbind(shapefile, a_average1)
    return (a_newdf)
}

Attempt to call function:

a_spmvavg(chicagoshp,chicagoshp$Assault)

Error output

Error in .subset2(x, i, exact = exact) : no such index at level 3

4.(function(x, i, exact) if (is.matrix(i)) as.matrix(x)[[i]] else .subset2(x, i, exact = exact))(x, ..., exact = exact)

3.[[.data.frame(shapefile, my_attribute)

2.shapefile[[my_attribute]]

1.a_spmvavg(chicagoshp, chicagoshp$Assault)


Solution

  • You've called it like this:

    a_spmvavg(chicagoshp,chicagoshp$Assault)
    

    and your function is defined like this:

    a_spmvavg <- function(shapefile, my_attribute) {
    

    So when you get here:

    a_val = shapefile[[my_attribute]]
    

    ...you are doing chicagoshp[[chicagoshp$Assault]]. Is that what you want?

    Or should you pass the name of the column, like: a_spmvavg(chicagoshp,"Assault") in which case shapefile[[myAttribute]] evaluates to chicagoshp[["Assault"]] which gets you the column values as a vector.