graphboi
graphboi

Reputation: 21

How can i create a function that returns a vector in R?

I want to create a function that returns its result as a vector, more specifically a function that returns the divisors of an input value and places them inside a vector.

divisors<-function(n){
  i <- 2
  c<-1

    x<-c()

      while(i <= n) {
        if(n%%i==0) {
        x[c]<-i  

        }
        i <- i + 1
        c<-c+1
        x


      }

    }

Upvotes: 0

Views: 55

Answers (1)

mickey
mickey

Reputation: 2188

You just need a return statement at the end of the function. You should also have c <- c+1 be inside the if statement. Here's an improved version of your function:

divisors <- function(n) {
    i <- 2
    c <- 1
    x <- c()
    while(i <= n) {
        if(n %% i==0) {
            x[c] <- i
            c <- c+1
            }
        i <- i + 1
        }
    return (x)
    }

A faster version might look like this:

divisors <- function(n) {
    x <- n / (n-1):1
    x[round(x) == x]
    }

which doesn't use the return statement, but returns the last evaluated expression (namely x[round(x) == x]).

Upvotes: 2

Related Questions