purrr package in R: How to use a changing parameter for a function that is applied to nested data with map()

Viewed 51

My problem is, that I don't want to use a fixed parameter (n=100) in the random_points() function applied to my nested data (last line of my code):

trk_id <- trk2 %>% mutate(random_used = map(hr1, random_points(.,n=100)))

Instead, for every id the amount of random points should be equal to the total number of observations of the id (data frame id_n). How can I work with map() and include a changing parameter for the function that is repeated?

This is my code using the data set amt_fisher included in the package amt:

library(purrr)
library(amt)
library(tidyverse)

trk <- amt_fisher %>% make_track(x_, y_, t_, id = id)

#nest data
data <- trk %>% nest(dat = -"id")

#calculate home range for every id (hr) and convert it to an sp object (hr1)
trk1 <- data %>% mutate(hr = map(dat, ~hr_kde(.,levels=0.95)))
trk1 <- trk1 %>% mutate(hr1 = map(hr, hr_isopleths)) 

#create a data frame with the number of observations for every id
animalsid <- unique(amt_fisher$id)
output <- list()

for (i in 1:length(unique(amt_fisher$id))){
  id1<- amt_fisher %>% filter(amt_fisher$id == animalsid[i])
  n <- length(id1$t_)
  output[[i]] <- list(n = n, id = animalsid[i])}

id_n <- do.call(rbind.data.frame, output)

#calculate n random points for every id within the calculated homerange of that id
trk_id <- trk1 %>% mutate(random_used = map(hr1, random_points(.,n=100)))
1 Answers

I think this is what you're looking for - we use map2 to supply two arguments to the random_points function, the first being the shapefile and the second being the number of points we'd like to generate. To get those both in one data frame to loop over, I use a quick left_join first:

trk_id <- trk1 %>% 
  left_join(id_n) %>%
  mutate(random_used = map2(hr1, n, random_points))
# A tibble: 4 x 6
  id    dat                     hr        hr1              n random_used                
  <chr> <list>                  <list>    <list>       <int> <list>                     
1 M1    <track_xyt [919 x 3]>   <kde [7]> <sf [1 x 4]>   919 <random_points [919 x 3]>  
2 M4    <track_xyt [8,958 x 3]> <kde [7]> <sf [1 x 4]>  8958 <random_points [8,958 x 3]>
3 F2    <track_xyt [3,004 x 3]> <kde [7]> <sf [1 x 4]>  3004 <random_points [3,004 x 3]>
4 F1    <track_xyt [1,349 x 3]> <kde [7]> <sf [1 x 4]>  1349 <random_points [1,349 x 3]>
Related