简体   繁体   English

在R-Project中对函数进行简单的for循环

[英]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. 我想在一个函数上创建一个for循环,该循环遍历向量的各项。 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? 循环中我在做什么错?

for loops are usually discouraged, try: 通常不建议使用for循环,请尝试:

 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])
}

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) 

A very simple solution for the output you want, but NOT using a for loop, could be achieved by: 可以通过以下方法实现所需输出的非常简单的解决方案,但不使用for循环:

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循环,则应使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM