Question

I am trying to write a function that reads a vector of numbers element wise and then storing them into a container. This is meant as a practice before I code something with if conditions.

My approach has failed so far, as the function returns a null statement, instead of what I wanted. I tried writing it in script form and it it worked, but somehow it malfunctioned when written as a function.

Here's the code I used.

amieven<-function(x){
         flag<-numeric()
         for(i in 1:length(x)){
                    flag[i]=x[i]
    }
}

The script version that worked fine looks like this:

flag<-numeric()
      for (i in 1:length(x))
      flag[i]=x[i]
Was it helpful?

Solution

Assuming your goal is to return the container called flag, then you simply need to specify flag as the return value.

amieven<-function(x){
  flag<-numeric()
  for(i in 1:length(x)){
    flag[i]=x[i]
  }
  return(flag)
}

or simply

amieven<-function(x){
  flag<-numeric()
  for(i in 1:length(x)){
    flag[i]=x[i]
  }
  flag
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top