R 如何在两个独立函数之间传递对象?
例如,我有以下两个函数,用户可以选择是先调用R 如何在两个独立函数之间传递对象?,r,function,arguments,environment,R,Function,Arguments,Environment,例如,我有以下两个函数,用户可以选择是先调用f1(),然后调用f2(),还是只调用f2(): 并且为a和b提供了值,接下来当他调用f2()时,我想让他只提供c参数,而不再需要为a和b插入调用f1()时使用的相同参数 例如: > x1 <- f1(a = 1, b = 2) > x1 [1] 3 > x2 <- f2(c = 2) Error in f2(c = 2) : argument "a" is missing, with no default >x1-x
f1()
,然后调用f2()
,还是只调用f2()
:
并且为a
和b
提供了值,接下来当他调用f2()
时,我想让他只提供c
参数,而不再需要为a
和b
插入调用f1()
时使用的相同参数
例如:
> x1 <- f1(a = 1, b = 2)
> x1
[1] 3
> x2 <- f2(c = 2)
Error in f2(c = 2) : argument "a" is missing, with no default
>x1-x1
[1] 3
>x2试试看
f1这可能对您的具体情况没有帮助,但总的来说,这就是我解决类似问题的方法:
# define a function that returns a vector
f1 <- function( a, b )
{
my_sum <- a + b
return(c ( my_sum, a, b ) )
}
# assign the returned vector to a variable for further use
# and extract the value you are interested in
x1 <- ( xx1 <- f1( a = 1, b = 2 ) )[ 1 ]
x1
[1] 3
xx1
[1] 3 1 2
# use the vector for default values for your 2nd function
f2 <- function( c, a = xx1[2], b = xx1[3] )
{
my_sum2 <- a + b + c
return(my_sum2)
}
# if f1() was called before, only one argument:
x2 <- f2( 3 )
x2
[1] 6
# or all three arguments in one call
x2 <- f2( 2, 4, 3 )
x2
[1] 9
#定义一个返回向量的函数
f1关于f2@实验者,假设x1处于全球环境中,情况可能并非如此(尽管上面的示例代码表明如此),这可能在这里起作用,但却是“火山边的生命”[(地狱,圆圈6)非常感谢您的回答。实际上,我正在寻找解决此问题的方法,而我给出的函数只是说明此问题的示例。但是,您建议的解决方案不够灵活,主要是因为这部分x1如果您更精确一点,也许我可以帮助您。只按值传递,而不按re传递引用在R中是一个挑战,但我已经习惯了。嘿@vaettchen。我现在唯一能想到的是:如果有一种方法(在f2()
的环境中)从f1()
的环境中提取a
和b
的值,那就太好了。再次感谢!
> x1 <- f1(a = 1, b = 2)
> x1
[1] 3
> x2 <- f2(c = 2)
Error in f2(c = 2) : argument "a" is missing, with no default
f1 <- function(a, b) {
my_sum <- a + b
a<<-a
b<<-b
return(my_sum)
}
a=0
b=0
f1 <- function(a, b) {
my_sum <- a + b
a<<-a
b<<-b
return(my_sum)
}
f1(4,4)
[1] 8
f2 <- function(a1=a, b1=b, c) {
my_sum2 <- a1 + b1 + c
return(my_sum2)
}
f2(c=3)
[1] 11
# define a function that returns a vector
f1 <- function( a, b )
{
my_sum <- a + b
return(c ( my_sum, a, b ) )
}
# assign the returned vector to a variable for further use
# and extract the value you are interested in
x1 <- ( xx1 <- f1( a = 1, b = 2 ) )[ 1 ]
x1
[1] 3
xx1
[1] 3 1 2
# use the vector for default values for your 2nd function
f2 <- function( c, a = xx1[2], b = xx1[3] )
{
my_sum2 <- a + b + c
return(my_sum2)
}
# if f1() was called before, only one argument:
x2 <- f2( 3 )
x2
[1] 6
# or all three arguments in one call
x2 <- f2( 2, 4, 3 )
x2
[1] 9