Reputation: 601
packages:
library(geosphere)
library(dplyr)
I have a list of data frames like this:
df_list
:
[[1]]
name X1 X2
1 A 1 1
2 A 1 2
3 A 2 2
4 A 2 1
[[2]]
name X1 X2
1 B 1 1
2 B 1 2
3 B 2 2
4 B 2 1
[[3]]
name X1 X2
1 C 1 1
2 C 1 2
3 C 2 2
4 C 2 1
I want to loop through each data frame in the list and calculate the area of the polygon the dataframe represents using areaPolygon()
from the geosphere
package. I can do this for one data frame like this:
name <- c("A","A","A","A")
X1 <- c(1,1,2,2)
X2 <- c(1,2,2,1)
df <- data.frame(name, X1, X2)
areaPolygon(df[,2:3])
I tried doing this with pipes by concatenating the list of data frames into one dataframe and grouping by name:
df_list_con <- do.call(rbind, df_list)
area <- df_list_concat %>% group_by(name) %>% areaPolygon(.[,2:3])
but it didn't work, giving the error message:
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘areaPolygon’ for signature ‘"grouped_df"’
Can I do this using mapply
or lapply
? I wouldn't know how to do it.
Upvotes: 0
Views: 97
Reputation: 2718
Grouping with group_by
is a dplyr-thing, to be used by dplyr functions such as summarise
and you shouldn't expect in general that functions from other packages will understand it.
What you need here is:
df_list_concat %>%
group_by(name) %>%
summarise(area = areaPolygon(cbind(X1, X2)))
Upvotes: 1