2

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?

4

1 回答 1

5

您的函数不会返回它创建的列表。您需要添加一个return命令:

result2 <- vector("list",10)

loop.function<-
  function(x,a,b){
    for (i in a:b)
  {
    result2[[i]] <- x*i
  }
  return(result2) # added this row
}

顺便说一句:可以使用以下命令创建此函数的较短版本lapply

myfun <- function(x, a = 1, b) {
    lapply(seq(a, b), "*", x)   
}
于 2013-01-22T10:29:20.507 回答