本文介绍了禁止(或隐藏)R中自定义函数的特定返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一个简单的R功能代码.
There is a simple R function code.
fx <- function(x){
lst <- list(a = x+1, b = x*2, c = x+c(1:100))
return(lst)
}
在这段代码中,我想隐藏'lst $ c'元素,因为数据很长.所以,我在下面尝试过
In this code, I want to hide 'lst$c' element because the data is long.So, I tried below
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
但是当我将此函数分配给对象时,我不想丢失"lst $ c"数据像这样.
but I don't wanna lose the 'lst$c' data when I assign this function to objectlike this.
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 ...
我该怎么做?
推荐答案
由@nrussell实现注释.你可以做这样的事情
To implement comments by @nrussell. You can do something like this
fx <- function(x){
lst <- list(a = x+1, b = x*2, c = x+c(1:100))
class(lst) <- "foo" # assign the class attribute to your returning result
return(lst)
}
print.foo <- function(x) print(x[c(1,2)]) # define a new print function for the foo class
fx(3) # now it prints only the first two elements
# $a
# [1] 4
# $b
# [1] 6
str(fx(3))
# List of 3
# $ a: num 4
# $ b: num 6
# $ c: num [1:100] 4 5 6 7 8 9 10 11 12 13 ...
# - attr(*, "class")= chr "foo"
这篇关于禁止(或隐藏)R中自定义函数的特定返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!