Gokul
Gokul

Reputation: 41

How to populate an empty vector in R using a function?

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.

Upvotes: 0

Views: 577

Answers (1)

ThomasIsCoding
ThomasIsCoding

Reputation: 101247

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

Upvotes: 2

Related Questions