I am new to this platform, so I hope I can make my problem clear as possible.
I have a dataset all_regions with the following column variables:
all_regions$region, all_regions$participantID, all_regions$longitude.coordinates, all_regions$latitude.coordinates, and all_regions$score.
I want to check the clustering per region for the variable score using the longitude and latitude coordinates. I have ~ 400.000 participants in 362 regions. I know what I have to do to calculate the Moran I value for one region:
#Extract data by region 1
region1 <- all_regions[all_regions$region == "region name"), ]
#generate a distance matrix for Moran I
dists1 <- as.matrix(dist(cbind(region1$longitude.coordinates, region1$latitude.coordinates))
#take the inverse of the matrix values for Moran I
dists.inv1 <- 1/dists1
#replace the diagonal entries with zero
diag(dists.inv1) <- 0
#replace Inf with NA
dists.inv1[sapply(dists.inv1, is.infinite)] <- NA
#calculate
result1 = Moran.I(dists.inv1$score,(is.na(dists.inv1)))
> result1
$observed [1] 0.001937182
$expected [1] -0.001221001
$sd [1] 0.007965195
$p.value [1] 0.6917378
The results provide information about the following statistics: $observed, $expected, $sd, and $p.value.
Doing this 362 times will take forever.
I want to create a loop or function in which the above described happens for each region and saves in CSV, a data frame of whatever with region name and the $observed, $expected, $sd, and $p.value values so that I can see the results back in one file. Any idea how?