Home > Software engineering >  Append a User Defined Function's output to a existing vector without printing the output in R
Append a User Defined Function's output to a existing vector without printing the output in R

Time:01-10

Suppose I have a blank vector -

ot_vec = c()

Now I have many user-defined functions e.g. Square_Calculator, SquareRoot_Calculator etc as defined below -

square_calculator <- function(x){
  sq = x*x
  sq
}
squareRoot_calculator <- function(x){
  sq_rt = sqrt(x)
  sq_rt
}

Now I want a code that will append the outputs of these functions one by one to the existing blank vector ot_vec w/o printing the outputs. Like the below -

After running these three lines of code -

square_calculator(2)
squareRoot_calculator(100)
square_calculator(5)

The Null Vector ot_vec should give output as -

Output

Note: I don't need anything like - ot_vec = c(ot_vec, Square_Calculator(2), SquareRoot_Calculator(100), Square_Calculator(5)) i.e., I want to modify the user-defined functions in a way that they instead of giving output, directly they will append output to the null vector.

I was trying something like -

My Try

CodePudding user response:

Maybe environments are what you are looking for. But the variable to be changed must be passed to the functions changing it.

square_calculator <- function(x, y, envir = parent.frame()){
  sq = x*x
  yname <- as.character(substitute(y))
  envir[[yname]] <- c(envir[[yname]], sq)
}
squareRoot_calculator <- function(x, y, envir = parent.frame()){
  sq_rt = sqrt(x)
  yname <- as.character(substitute(y))
  envir[[yname]] <- c(envir[[yname]], sq_rt)
}

ot_vec <- NULL
square_calculator(2, ot_vec)
squareRoot_calculator(100, ot_vec)
square_calculator(5, ot_vec)
ot_vec
#> [1]  4 10 25

Created on 2023-01-09 with reprex v2.0.2

CodePudding user response:

You need to assign to a variable in the parent frame. That is to assign a value to a name. One solution would be to call the modified square_calculator with the name of the variable:

ot_vec <- c()

square_calculator <- function(x, vec) {
  sq <- x*x
  assign(vec,
         c(get(vec), sq),
         env = parent.frame())
}

square_calculator(10, "ot_vec")
> ot_vec
[1] 100
  • Related