Reputation: 3039
I experience some trouble trying to create a function that contains a loop in R. The loop works fine but when I put it inside the body of my function it won't write any Output any more.
So given my data with:
df1<-data.frame(a=sample(1:50,10),b=sample(1:50,10),c=sample(1:50,10))
I create a vector to store my results and a loop with some function
result <- vector("list",10)
for (i in 1:10)
{
result[[i]] <- df1*i
}
when I try to create a function like this
# make the loop a function
result2 <- vector("list",10)
loop.function<-
function(x,a,b){
for (i in a:b)
{
result2[[i]] <- x*i
}
}
loop.function(df1,1,10)
I get no data in "result2". So I think there is some basic problem in the syntax. Can anyone help me out?
Upvotes: 2
Views: 5116
Reputation: 81683
Your function does not return the list it created. You need to add a return
command:
result2 <- vector("list",10)
loop.function<-
function(x,a,b){
for (i in a:b)
{
result2[[i]] <- x*i
}
return(result2) # added this row
}
By the way: A shorter version of this function could be created with lapply
:
myfun <- function(x, a = 1, b) {
lapply(seq(a, b), "*", x)
}
Upvotes: 5