pythonrfor-loopgwmodel

how to for loop a variable inside an R functon


I am a python user new to R. Right now I am dealing with the R package GWmodel.

Looking at the function for the basic GWR, this looks like:

gwr.res <- gwr.basic(GenEl2004 ~ DiffAdd + LARent + SC1 + Unempl + LowEduc + Age18_24 + Age25_44 + Age45_64, data = Dub.voter, bw = 100,  kernel = "bisquare", adaptive = TRUE, F123.test = TRUE)

What I need is to collet the mean of the estimate parameters of each variable and append it in a list for any given value of bw (bandwidth).

in python terms this would be like:

LARentMean = []
SC1Mean = []
UnenmplMean = []
LowEducMean = []
Age18_24Mean = []
Age25_44Mean = []
Age45_64Mean = []


for i in range (20,400):
    gwrres = gwr.basic(GenEl2004 ~ DiffAdd + LARent + SC1 + Unempl + LowEduc + Age18_24 + Age25_44 + Age45_64, data = Dub.voter, bw = i,  kernel = "bisquare", adaptive = TRUE, F123.test = TRUE)
    a = gwrres(LARent).mean()    #a <- mean(gwrres$SDF$LARent)
    b = gwrres(SC1).mean()       #b <- mean(gwrres$SDF$SC1)
    c = gwrres(Unenmpl).mean()   #c <- mean(gwrres$SDF$Unempl)
    d = gwrres(lowEduc).mean()   #d <- mean(gwrres$SDF$LowEduc)
    e = gwrres(Age18_24).mean()  #e <- mean(gwrres$SDF$Age18_24)
    f = gwrres(Age25_44).mean()  #f <- mean(gwrres$SDF$Age25_44)
    g = gwrres(Age45_64).mean()  #g <- mean(gwrres$SDF$Age45_64)
    LARentMean.append(a)
    SC1Mean.append(b)
    UnenmplMean.append(c)
    LowEducMean.append(d)
    Age18_24Mean.append(e)
    Age25_44Mean.append(f)
    Age45_64Mean.append(g)

Solution

  • You can use lapply which will loop to a list, e.g.:

    l = lapply(20:400, function(i){
        gwr.basic(GenEl2004 ~ DiffAdd + LARent + SC1 + Unempl + LowEduc + 
            Age18_24 + Age25_44 + Age45_64, data=Dub.voter, bw=i,
            kernel="bisquare", adaptive=T, F123.test=T)
    })
    

    I have no idea what gwr.basic generates as output, so you may want an extra line to only take the mean (if it puts out more information).