Paula
Paula

Reputation: 703

Give multiple elements to a function & assign them

I have the following function (of course is a little more complex than this!):

my_function <- function(id_table) {
  
  data("mtcars")
  
    if (id_table == "1_1") { 
      
      df <- mtcars %>% 
        filter(mpg > 19) 
      
      df
      
      
  } else if (id_table == "1_2") {
      
    df <- mtcars %>% 
      filter(disp < 100) 
    
    df
  } else {
    
    df <- mtcars %>% 
      select(vs, am, gear)
    
    df  
    }
}

It works individually, as in:

foo <- my_function("1_1")

I want to give the function multiple inputs in a vector and another one to assign the objects resulting:

input_vector <- c("1_1", "1_2", "1_3")
names_vector <- sapply(input_vector, str_c, "t", sep = "")

I want to do what I did individually but instead giving my_function the input_vector and assign each one with the names provided by the names_vector. For instance, automatize this:

1_1t <- my_function("1_1")
1_2t <- my_function("1_2")
1_3t <- my_function("1_3") 

PS: I want to put the "t" before the corresponding value of the vector but I do not know how.

Upvotes: 3

Views: 60

Answers (1)

akrun
akrun

Reputation: 887941

We can use lapply to loop over the 'input_vector' which is named, apply the function and store in a list

out <- lapply(setNames(input_vector, names_vector), my_function)

It may be better to store in list and extract as

out$`1_1t`

instead of creating objects in the global environment. If we need use

list2env(out, envir = .GlobalEnv)

-check the objects

> head(`1_1t`)
                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4      21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710     22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Merc 240D      24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230       22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
> head(`1_2t`)
                mpg cyl disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4 78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4 75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4 71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4 79.0  66 4.08 1.935 18.90  1  1    4    1
Lotus Europa   30.4   4 95.1 113 3.77 1.513 16.90  1  1    5    2
> head(`1_3t`)
                  vs am gear
Mazda RX4          0  1    4
Mazda RX4 Wag      0  1    4
Datsun 710         1  1    4
Hornet 4 Drive     1  0    3
Hornet Sportabout  0  0    3
Valiant            1  0    3

Upvotes: 3

Related Questions