0

First of all, I am initializing an empty vector and I want to populate it whenever I call the function. I want the element added to be added to the empty vector and so on but, when I call the function nothing happens so I not sure what I am doing wrong. Any help is appreciated.

 empty_vec<-c()

func<-function(num){
  
  for (numbers in num) {   
    i<-sqrt(numbers)
    empty_vec<- c(empty_vec,i)
  }
}

func(4) # When calling the func,4 isn't getting added to the empty_vec.
1
  • 2
    (1) Reaching out from the inside of your function to read an external variable is bad practice, and can lead to at best difficult-to-troubleshoot code. Worse, <- will not overwrite the value of the empty_vec outside of func, it will make a "copy" of the data within the function that masks it, and when the function exits, that updated copy will cease to exist. (2) There are functions for doing that (see <<- and assign), but they should not be used regularly, and suggest a poor design. I discourage them. Commented Dec 31, 2020 at 1:26

1 Answer 1

2

You should initialize empty_vec within func and return it (so you should put empty_vec at the bottom as well), e.g.,

func <- function(num) {
  empty_vec <- c()
  for (numbers in num) {
    i <- sqrt(numbers)
    empty_vec <- c(empty_vec, i)
  }
  empty_vec
}

such that

> func(c(4, 5, 6, 7))
[1] 2.000000 2.236068 2.449490 2.645751

Since what you are doing is to calculate sqrt, you can do it just via

> sqrt(c(4,5,6,7))
[1] 2.000000 2.236068 2.449490 2.645751
Sign up to request clarification or add additional context in comments.

1 Comment

More generally, empty_vec is unnecessary for many easily-defined operations, even if it's not a built-in function. For example, func <- function(num) log(num) * sqrt(num) + 10 (or whatever other arbitrary operations you like) can simply take a vector as input: func(c(4, 6, 9)).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.