Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R- assign inside a function

Tags:

function

r

assign

I need to create a data frame from a function entering another data frame name and reshaping the data. The issue comes when I need to named the output after a transformation of the input table name. My code so far is:

tablaXYZ<-data.frame(a=seq(1,2,1), 'X1'=seq(2,3,1), 'X2'=seq(3,4,1))
rownames(tablaXYZ)<-c('X1', 'X2')

And the function I worte is:

creaMelts<-function(tbl){
    library(reshape2)
    texto<-deparse(substitute(tbl))
    tbl2<-melt(tbl, id.vars=rownames(tbl))
    texto2<-substr(texto,4,nchar(texto))
    colnames(tbl2)<-c('userId','movieId', texto2)
    tblName<<-paste0('df', texto2)
    print(paste('tblName', tblName, ' '))
    assign(tblName, tbl2)
    return(assign(tblName, tbl2))
}

When I run:

creaMelts(tablaXYZ)

I get:

"tblName dflaXYZ  "

So, considering "assign" works returning in the object given in the 2nd place with the name stored in the object in the 1st place, like:

 `m<-'hola'`
 assign(m, tablaXYZ)

And then I ask for m, I get:

"hola"

But if I ask for "hola" I get the table:

hola
   a X1 X2
X1 1  2  3
X2 2  3  4

I thought I would have a data frame named "dflaXYZ" with the values:

  userId movieId laXYZ NA
1      2       3     a  1
2      3       4     a  2

But if I run:

 dflaXYZ

I only get:

"dflaXYZ"

and if I run for example:

a<-creaMelts(tablaXYZ)

And then ask for "a", I get the desired table.

  userId movieId laXYZ NA
1      2       3     a  1
2      3       4     a  2

I need to get the same table but named in this case dflaXYZ (deleting the 1st 3 letters and adding df to the input table name).

like image 547
GabyLP Avatar asked Jun 16 '26 11:06

GabyLP


1 Answers

We need to use envir argument for the assign to access the environment outside the function.

creaMelts<-function(tbl){
   library(reshape2)
   texto<-deparse(substitute(tbl))
   tbl2<-melt(tbl, id.vars=rownames(tbl))
   texto2<-substr(texto,4,nchar(texto))
   colnames(tbl2)<-c('userId','movieId', texto2)
   tblName<<-paste0('df', texto2)
    print(paste('tblName', tblName, ' '))
    assign(tblName, tbl2, envir = parent.frame() )

 }

creaMelts(tablaXYZ)
dflaXYZ
#  userId movieId laXYZ NA
#1      2       3     a  1
#2      3       4     a  2
like image 154
akrun Avatar answered Jun 19 '26 03:06

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!