从函数输入命名R中的对象
如何从函数输入创建变量?比如说,从函数输入命名R中的对象,r,function,R,Function,如何从函数输入创建变量?比如说, test <- function(var_name, num) { var_name <<- 2 + num } test(hello, 2) test我想你想要的是这样的: test <- function(var_name, num) { assign(var_name, num + 2, envir = .GlobalEnv) } test("hello", 2) 测试不清楚您在问什么。您期望的结果是什么?R中
test <- function(var_name, num) {
var_name <<- 2 + num
}
test(hello, 2)
test我想你想要的是这样的:
test <- function(var_name, num) {
assign(var_name, num + 2, envir = .GlobalEnv)
}
test("hello", 2)
测试不清楚您在问什么。您期望的结果是什么?R中的函数并不意味着改变其自身范围之外的变量值。对于R来说,这不是一个好的设计。函数应该返回分配给变量的值;更像是hello,或者如果您坚持test(hello,2)
,您可以使用assign(deparse(replacement(var)),num+2,envir=.GlobalEnv)
——但是请参见上面@MrFlick的评论。