yPennylane
yPennylane

Reputation: 772

Simple for loop on a function in R-Project

I want to create a for loop on a function, which iterates over the items of a vector. I want to produce a vector consisting of the results:

funk <- function(x){return (x+1)}

ul <- seq(0,1,0.001)
test1 <- NULL
for (i in ul){
    test1 <- data.frame(column = rbind(test1, funk(ul[i])))
    }

I get the result

test1
  column
1 1

I would like to get

  column
1 1
2 1.001
3 1.002
...

What am I doing wrong within the loop?

Upvotes: 0

Views: 103

Answers (3)

COLO
COLO

Reputation: 1114

A very simple solution for the output you want, but NOT using a for loop, could be achieved by:

test1 <- data.frame(column=funk(ul))

head(test1)
  column
1  1.000
2  1.001
3  1.002
4  1.003
5  1.004
6  1.005

If you still want a for-loop, I should use:

for (i in 1:length(ul)){
     d <- data.frame(column=funk(ul[i]))
     if(exists('test1')) {
       test1<-rbind(test1,d)
     } else{
       test1<-copy(d)
     }
}

head(test1)
  column
1  1.000
2  1.001
3  1.002
4  1.003
5  1.004
6  1.005

Upvotes: 0

Mario M.
Mario M.

Reputation: 872

Within a loop it would be:

funk <- function(x){return (x+1)}

ul <- seq(0,1,0.001)
test1 = list()

for (i in 1:length(ul)){
  test1[[i]] = data.frame(column= funk(ul[i]))
}
test1  = do.call("rbind", test1) 

Upvotes: 0

Mouad_Seridi
Mouad_Seridi

Reputation: 2716

for loops are usually discouraged, try:

 sapply(ul, funk)

if you really want to use for loops, here is the solution

funk <- function(x){return (x+1)}

ul <- seq(0,1,0.001)

## always create the vector first so R allocates memory 

test1 <- rep(NA, length(ul))


for (i in 1:length(ul))
  {
  test1[i] <-  funk(ul[i])
}

Upvotes: 1

Related Questions