Automate script by changing str_detect?

Viewed 33

I am using this script to produce a table. In the second line, for collectionName, I am using "Organization X". I have many different organizations (Org Y, Org Z, .....) to create this table for. Is there a way to automate this? And to automate the naming of the object (currently "orgx" below)?

orgx <- df %>%
  filter(str_detect(collectionName, c("Organization X"))) %>%
  filter(str_detect(Year, paste(years, collapse = "|"))) %>%
  corpus(text_field = "text") %>%
  tokens(remove_punct = TRUE) %>%
  tokens_select(stopwords('english'),selection='remove') %>%
  tokens_tolower(keep_acronyms = FALSE) %>%
  tokens_lookup(dictionary = dict, nomatch = TRUE) %>%
  dfm() %>%
  dfm_group(groups = "Title") %>%
  dfm_weight(scheme = "prop") %>%
  as.data.frame() %>%
  mutate_at(vars(keyterms, true), funs(round(., 4)))
1 Answers

Get the column names specific to that organizations as vector, use that as pattern in str_detect by looping over the vector in map and return the output in a list

library(dplyr)
library(purrr)
library(stringr)
vec <- c("Organization X", "Organization Y")
out <- map(vec, ~ 
         df %>%
  filter(str_detect(collectionName, .x)) %>%
  filter(str_detect(Year, paste(years, collapse = "|"))) %>%
  corpus(text_field = "text") %>%
  tokens(remove_punct = TRUE) %>%
  tokens_select(stopwords('english'),selection='remove') %>%
  tokens_tolower(keep_acronyms = FALSE) %>%
  tokens_lookup(dictionary = dict, nomatch = TRUE) %>%
  dfm() %>%
  dfm_group(groups = "Title") %>%
  dfm_weight(scheme = "prop") %>%
  as.data.frame() %>%
  mutate_at(vars(keyterms, true), funs(round(., 4)))
)
names(out) <- sub("^(...).*\\s+(\\S)$", "\\1\\2", vec)

It may be better to keep the output in a list. But, if we need to assign it to different objects, it can be done with list2env or assign

list2env(out, .GlobalEnv)
Related