Define global variable using function argument in R

后端 未结 2 1597
春和景丽
春和景丽 2021-02-04 16:52

I\'m trying to write a function in R that drops columns from a data frame and returns the new data with a name specified as an argument of the function:

drop <         


        
2条回答
  •  有刺的猬
    2021-02-04 17:06

    Use the assign() function.

      assign("new.data", my.data[,-col], envir = .GlobalEnv) 
    

    The first argument should be a string. In this case, the resultant global variable will be named "new.data". If new.data is the name itself, drop the quotes from the function call.

    <<- does not always assign to the global environment.

    In general, however, it is better to return things from a function than set global variables from inside a function. The latter is a lot harder to debug.

提交回复
热议问题