在R中抑制(或隐藏)自定义函数的特定返回值

时间:2016-07-06 14:03:10

标签: r function return

有一个简单的R功能代码。

fx <- function(x){

  lst <- list(a = x+1, b = x*2, c = x+c(1:100))
  return(lst)

}

在这段代码中,我想隐藏'lst $ c'元素,因为数据很长。 所以,我试过下面的

fx <- function(x){

 lst <- list(a = x+1, b = x*2, c = x+c(1:100))
 return(lst[c(1,2)])

}

object <- fx(1)
object

并获取

###
$a
[1]2

$b
[1]2

fx <- function(x){

 lst <- list(a = x+1, b = x*2, c = x+c(1:100))
 invisible(lst)

}

object <- fx(1)
object

###
$a
[1]2

$b
[1]2

$c
[1]2 3 4 5 ....101

但是当我将此函数分配给object时,我不想丢失'lst $ c'数据 像这样。

object <- fx(2)
object

## No return 'lst$c'.
$a
[1]2

$b
[1]2

str(object)

## not include 'lst$c'
List of 2
$ a: num 2
$ b: num 2

所以,我想......

object

###
$a
[1]2

$b
[1]2

str(object)

## still have lst$c data in the data structure
List of 3
$ a: num 2
$ b: num 2
$ c: num [1:100] 2 3 4 5 6 7 ...

我该怎么做?

1 个答案:

答案 0 :(得分:2)

实施@nrussell的评论。你可以做这样的事情

HttpSessionBindingListener