在R中使用函数参数定义全局变量

在R中使用函数参数定义全局变量

本文介绍了在R中使用函数参数定义全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在R中编写一个函数,它从数据框中删除列,并返回一个名称为函数参数的新数据:

<$ (my.data,col,new.data){
new.data<< - my.data [, - col]
return(new.data)
}

所以在上面的例子中,我想要一个新的数据框在调用函数后存在,该函数被命名为用户输入的第三个参数。



当我调用函数时,返回正确的数据框,但那么如果我然后尝试在全局环境中使用新的数据框,我会得到 object not found 。我想通过使用全局定义 new.data << - 运算符。



有人可以帮助我了解发生了什么事,并且是否有办法实现这一目标?

我发现和

>使用 assign()函数。

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

第一个参数应该是一个字符串。在这种情况下,生成的全局变量将被命名为new.data。如果 new.data 是名称本身,请从函数调用中删除引号。

<< - 并不总是分配给全局环境。一般来说,最好从函数中返回一些东西,而不是从函数内部设置全局变量。后者更难调试。


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 <- function(my.data,col,new.data) {
new.data <<- my.data[,-col]
return(new.data)
}

So in the above example, I want a new data frame to exist after the function is called that is named whatever the user inputs as the third argument.

When I call the function the correct data frame is returned, but then if I then try to use the new data frame in the global environment I get object not found. I thought by using the <<- operator I was defining new.data globally.

Can someone help me understand what's going on and if there is a way to accomplish this?

I found this and this that seemed related, but neither quite answered my question.

解决方案

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.

这篇关于在R中使用函数参数定义全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 10:21