R- assign inside a function

前端 未结 1 1768
慢半拍i
慢半拍i 2021-01-13 03:38

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

相关标签:
1条回答
  • 2021-01-13 03:57

    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
    
    0 讨论(0)
提交回复
热议问题