milan
milan

Reputation: 11

R function to populate a vector

I want to populate a vector with item returned by a function. but I am not being able to do this

w=NULL
fn=function(x){

for (i in x){ if (i%%2==1){ w <- c(w, i) 
 } print (w)

} return (w) }

after executing fn (c(1,3,4,7,8,9))

I still get

w NULL

what I was expecting is

w [1] 1 3 7 9

Upvotes: 1

Views: 251

Answers (2)

dmontaner
dmontaner

Reputation: 2165

Usually the w you want to use inside your function is different than the one you use outside in your R session (despite both being called the same). That is why your function does not change the w in your R session after being executed and it stays as NULL.

If you really want to change the value of your w in the R session within the function you can use the assignment <<-

w = NULL
fn = function (x) {
    for (i in x) {
        if (i %% 2 == 1) {
            w <<- c (w, i)  ## here is the change
        }
        print (w)
    }
    return (w) # and this is not strictly needed
}

fn (c(1,3,4,7,8,9))

w

[1] 1 3 7 9

Upvotes: 1

SymbolixAU
SymbolixAU

Reputation: 26258

This works as R code, but is it what you're expecting?

w <- NULL

fn <- function(x){

    for(i in x){ 

        if(i%%2==1){
            w <- c(w, i) 
        } 
        print (w)
    }
return (w)
}

x <- c(1,3,4,7,8,9)
fn(x)
# [1] 1
# [1] 1 3
# [1] 1 3
# [1] 1 3 7
# [1] 1 3 7
# [1] 1 3 7 9
# [1] 1 3 7 9

Do you in fact just want

x[x%%2==1]
# [1] 1 3 7 9

Upvotes: 1

Related Questions