Reputation: 772
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
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
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
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