Search code examples
rassign

Create new objects in R based on input file with information on these objects


Assume I have the following lookup table:

object_lookup <- data.frame(name  = c(new_var_1, new_var_2, new_var_2),
                            value = c(7, "ABC", "XYZ"),
                            type  = c("numeric", "character", "character"))

I now want to go through that list and create the objects based on the name value, assign them the value based on the value column and want to make sure they have the type provided in type.

I know how I can create one new object at a time with assign, but I'm struggling with a) automating the process and b) making sure that the type is correct and c) how to deal with cases where more than one value is supposed to be assigned. I thought about some sort of apply function here?

Sth. like apply(object_lookup, 1, function(x) {assign(name, value); if (type == "numeric) as.numeric(x)}

Ultimately, I want to have two new R objects in that example:

new_var_1 <- c(7) # numeric
new_var_2 <- c("ABC", "XYZ") # character

Any ideas?


Solution

  • Your first column in data.frame should be character vector then you can try something like this:

    library(dplyr)
    library(purrr)
    
    object_lookup %>%
      mutate(across(everything(), as.character)) %>%
      group_by(name) %>%
      summarise(value = list(value), type = unique(type)) %>%
      {if(any(count(., name)$n > 1)) stop("wrong input") else .} %>%
      mutate(value = map2(value, type, ~do.call(paste0("as.", .y), args = list(.x)))) %>%
      select(name, value) %>%
      pwalk(~assign(.x, .y, envir = globalenv()))
    

    stop is there if input is wrong (same variable with different types)