0

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)

}

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

and get

###
$a
[1]2

$b
[1]2

and

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

but I don't wanna lose the 'lst$c' data when I assign this function to object like 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

So, I want...

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 ...

How can I do this?

KS Lee
  • 81
  • 1
  • 6
  • 5
    You will most likely need a custom class & corresponding `print` method for the object you are returning. – nrussell Jul 06 '16 at 14:05
  • See [here](http://stackoverflow.com/questions/10938427/example-needed-change-the-default-print-method-of-an-object) for an example – alexis_laz Jul 06 '16 at 14:08
  • 1
    Possible duplicate of [Hiding a result of a function in R](http://stackoverflow.com/questions/37396203/hiding-a-result-of-a-function-in-r) – dww Jul 06 '16 at 17:12

1 Answers1

2

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"
Psidom
  • 209,562
  • 33
  • 339
  • 356
  • 2
    As a side note, `structure` can be helpful for writing this type of operation more succinctly: `fx <- function(x) { structure(list(a = x + 1, b = x * 2, c = x + 1:100), class = "foo") }`. – nrussell Jul 06 '16 at 14:19