如何在两个独立函数之间传递对象?

时间:2015-07-01 09:34:17

标签: r function arguments environment

我有(例如)以下两个功能,用户选择是先呼叫f1()再呼叫f2(),还是只呼叫f2()

f1 <- function(a, b) {
  my_sum <- a + b
  return(my_sum)
}

f2 <- function(a, b, c) {
  my_sum2 <- a + b + c
  return(my_sum2)
}

如果用户首先拨打f1()然后f2(),则他知道当他呼叫a时,他需要分配给bf1()的相同值当他致电a时,会被分配到bf2()。问题是如果他打算

 x1 <- f1(a = 1, b = 2)

并向ab提供了值,接下来当他调用f2()时我想让他只提供c参数而不再需要为ab调用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 插入相同的参数。

例如:

x2 <- f2(c = 2)

当他致电f2()时,我希望ab获取x1 <- f1(a = 1, b = 2).footer{ display: inline-block; text-align: center; margin-left: auto; margin-right: auto; width: 100%; position:absolute; bottom:0px; } 的值。 我怎样才能做到这一点? 任何帮助将不胜感激,

最佳,

阿亚拉

2 个答案:

答案 0 :(得分:0)

尝试

f1 <- function(a, b) {
  my_sum <- a + b
  a<<-a
  b<<-b
    return(my_sum)
}

对于f2,您还需要声明全局变量(<<-

例如

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

答案 1 :(得分:0)

这可能对您的具体情况没有帮助,但总的来说,这就是我解决类似问题的方法:

# 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