adamrusn
adamrusn

Reputation: 29

How to create a command/function/shortcut to call a chunk of codes in R?

Is there a way to create a command/function/shortcut to call a block of codes? It is the same as we block some lines of codes in a script, then press Ctrl+Enter (in Windows). I want to call the code chunk without the script. I only know that we can make a function with variables. Of course, it cannot be applied with something like this below because we have to input the variable, right?

make_dfs<- function() {
  df1<-data.frame(a=1, b=2, c=3)
  df2<-data.frame(d=4, e=5, f=6)
  df3<-data.frame(g=7, h=8, i=9)}

In the example above, I want to create df1, df2, and df3 instantly by only typing "make_dfs". The motivation for this is when I want to clean the temporary elements in my environment, I tend to think "maybe in the future I will need to create the same elements again".

I could not find suitable keywords for this issue, making my search was unsuccessful. I am still very new to R and programming. Please enlighten me, if there are some ways to do it or if my thinking is not correct.

Thank you.

Upvotes: 0

Views: 247

Answers (2)

akrun
akrun

Reputation: 887028

We can use assign

make_dfs <- function() {
   assign("df1", data.frame(a = 1, b = 2, c = 3), .GlobalEnv)
   assign("df2", data.frame(d = 4, e = 5, f = 6), .GlobalEnv)
   assign("df3", data.frame(g = 7, h = 8, i = 9), .GlobalEnv)
}

-testing

make_dfs()

-check the objects in the global env

> df1
  a b c
1 1 2 3
> df2
  d e f
1 4 5 6
> df3
  g h i
1 7 8 9

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388862

Are you looking to create df1, df2, df3 in global environment?

Try this -

make_dfs<- function() {
  list2env(list(df1 = data.frame(a=1, b=2, c=3),
       df2 = data.frame(d=4, e=5, f=6),
       df3 = data.frame(g=7, h=8, i=9)), .GlobalEnv)
}
make_dfs()

Upvotes: 1

Related Questions