How do I iterate through shapefile attribute tables and write results to a new .csv table in R?

StackOverflow https://stackoverflow.com/questions/21974330

  •  15-10-2022
  •  | 
  •  

Question

I would like to loop through an attribute table (e.g. INPUT), determine the minimum distance there is an interaction, and write that distance plus the FID to a new table (e.g. OUTPUT). I have exported the attribute table from ArcGIS as a .csv for simplicity.

Here is some simplified example data http://i.imgur.com/blDQfVS.png

For example, for FID 001 there was no interaction, for 002 the interaction was at 5000 m, for 003 there was an interaction at 2000 m, and for 004 there was an interaction at 0 m.

I have the logic figured out, but I am having difficulty writing the output to a table. This is what I have come up with so far (I'm just using print here for troubleshooting purposes):

# Process rows and determine the minimum zone of influence
for (i in 1:nrow(INPUT)){
  ifelse(INPUT$BUFFER_0k[i]>0, print("0"), 
         ifelse(INPUT$BUFFER_2k[i]>0, print("2000"), 
                ifelse(INPUT$BUFFER_5k[i]>0, print("5000"), print("NA"))))

I have tried replacing print with things like

csvFile="C:\\...\\output.csv"
write.csv(c(INPUT$FID[i], "0"), file=csvFile, append=TRUE)

and I cannot even get something like the following to work in place of a simple print statement

print(c(INPUT$FID[i]>0, "0"))

I appreciate any suggestions.

Was it helpful?

Solution

Your code uses print which immediately prints the values – that’s not what you want. You want to separately (a) calculate the result and (b) write the result table into a file.

First, here’s a function which transforms a single row:

get_dist = function (row) {
    index = which(row > 0)[1]
    if (is.na(index)) NA else switch(index, 0, 2000, 5000)
}

It works by looking which is the first index that is >0, if any. switch translates that index into the distance.

Now we apply (literally) the function to the input matrix:

result = apply(input, 1, get_dist)

But this result is actually a vector:

result
#  001  002  003  004
#   NA 5000 2000    0

– we want a matrix or data frame:

result = data.frame(distance = result)
result
#     distance
# 001       NA
# 002     5000
# 003     2000
# 004        0

And now we can write it to a file:

write.csv(result, csv_file, append = TRUE)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top