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.
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()