Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replicate function in R returns NULL

Tags:

r

replicate

I am confused about the output from the replicate function in R, I am trying to use it in two different ways, that (in my mind) should give a matrix as output!

so, if I use

replicate(5, seq(1,5,1))

I get a matrix 5x5

    [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    1    1
[2,]    2    2    2    2    2
[3,]    3    3    3    3    3
[4,]    4    4    4    4    4
[5,]    5    5    5    5    5

..and that's ok, I get that...

but, if I instead use:

replicate(5, for(i in 1:5){print(i)})

I get the following:

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[[1]]
NULL

[[2]]
NULL

[[3]]
NULL

[[4]]
NULL

[[5]]
NULL

can anyone explain me why does this happen? thanks :)

like image 764
TriRook Avatar asked Oct 31 '13 21:10

TriRook


People also ask

Why does a function return NULL in R?

NULL represents the null object in R. NULL is used mainly to represent the lists with zero length, and is often returned by expressions and functions whose value is undefined. as. null ignores its argument and returns the value NULL .

What does replicate () do in R?

replicate() function in R Programming Language is used to evaluate an expression N number of times repeatedly.


2 Answers

A for loop returns NULL. So in the second case, the replicate function is executing for(i in 1:5){print(i)} five times, which is why you see all those numbers printed out.

Then it is putting the return values in a list, so the return value of the replicate call is a list of five NULLs, which gets printed out. Executing

x<-replicate(5, for(i in 1:5){print(i)})
x

should clarify.

like image 147
mrip Avatar answered Oct 16 '22 11:10

mrip


As @mrip says a for-loop returns NULL so you need to assign to an object within the loop, and return that object to replicate so it can be output. However, mrip's code still results in NULLs from each iteration of the replicate evaluation.

You also need to assign the output of replicate to a name, so it doesn't just evaporate, er, get garbage collected. That means you need to add the d as a separate statement so that the evaluation of the whole expression inside the curley-braces will return 'something' rather than NULL.

d <- numeric(5); res <- replicate(5, { 
                            for(i in 1:5){d[i] <- print(i)} ; d}
                                  )
[1] 1
[1] 2

snipped
[1] 4
[1] 5
> res
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    1    1
[2,]    2    2    2    2    2
[3,]    3    3    3    3    3
[4,]    4    4    4    4    4
[5,]    5    5    5    5    5
like image 24
IRTFM Avatar answered Oct 16 '22 09:10

IRTFM