R:函数如何为将在函数外持续存在的变量赋值? [英] R: How can a function assign a value to a variable that will persist outside the function?

查看:55
本文介绍了R:函数如何为将在函数外持续存在的变量赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能很容易,但我对环境感到困惑.我想使用对函数的调用来为变量赋值,但我需要能够在调用后使用该变量.但是,我假设函数创建的变量只存在于函数环境中.简而言之,我需要类似于全局变量的东西(但我是 R 的初学者).

This is probably easy but I am confused as hell with environments. I would like to use a call to a function to assign a value to a variable, but I need to be able to use that variable after the call. However, I assume, the variable created by the function only exist within the function environment. In short, I need something akin to a global variable (but I am a beginner with R).

以下代码:

assignvalue = function(varname){
        assign(varname,1)
     }
assignvalue("test")
test

返回 Error: object 'test' not found 而我希望它等同于

returns Error: object 'test' not found whereas I would like it to be equivalent to

test <- 1
test

我在 assign 的文档中阅读了一些关于环境的内容,但我无法理解.

I read something in the documentation of assign about environments, but I could not understand it.

推荐答案

foo 是你函数的一个参数.只需这样做:

Say foo is a parameter of your function. Simply do this:

assignvalue <- function(foo) {
        varname <<- foo
}
assignvalue("whatever")
varname

变量 varname 将指向值 "whatever".

这篇关于R:函数如何为将在函数外持续存在的变量赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆