I'm working with sf
objects and I have a question about applying user-defined functions to data frames. This is a silly example, but it is similar to what I'm trying to do with a more complicated problem. I have a data frame called names
that has two columns, each with the name of a county. I also read in the North Carolina data included with the sf
package.
require(sf)
name_1 <- c('Ashe','Alleghany','Surry')
name_2 <- c('Currituck','Northampton','Hertford')
names <- data.frame(cbind(name_1,name_2))
nc <- st_read(system.file("shape/nc.shp", package="sf"))
What I'm trying to do is create a function that goes down each row of my data frame names
, takes the name out of the name_1 column and the name out of the name_2 column, and sees if they intersect using the geometric data in nc
. I have:
check_intersection <- function(x){
return(st_intersects(nc[nc$NAME== x$name_1,],nc[nc$NAME==x$name_2,],sparse = FALSE))
}
apply(names,1,check_intersection)
But this yields an error of Error in x$name_1 : $ operator is invalid for atomic vectors
. How do I tell the function to get the character values out of the appropriate columns, for each row in names
?