ixodid
ixodid

Reputation: 2400

Apply own function across vector

I am using a dataframe as a lookup table. Given the name of an financial institution (FI) return its ID.

I have a function that can do that for a single (FI) at a time. I wish to use this function with a vector of a few dozen FIs.

So feeding companies into the function should return 12 and 14.

Is this a job for the Tidyverse map function?

library("tidyverse")

groups_df <- tibble(
  fi = c("a", "b", "c"),
  id = c(10, 12, 14)
)
companies <- c("b", "c")

group_id_lookup <- function(new_comp, groups_df){
  group_id_idx <- which(groups_df$fi == new_comp)
  group_id <- pull(groups_df[group_id_idx, 2])
  print(group_id)
  # Do more things
}


group_id_lookup("b", groups_df) # OK
group_id_lookup("c", groups_df) # OK

# Wrong
companies %>% 
  map(group_id_lookup)

Upvotes: 1

Views: 35

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388992

A join or match option should be a better approach here.

groups_df$id[match(companies, groups_df$fi)]
#[1] 12 14

Upvotes: 1

Related Questions