简体   繁体   English

R函数在向量上使用FOR循环

[英]R function with FOR loop on a vector

Surely a facepalm question, sorry. 当然是一个facepalm问题,对不起。 I have been trying to RTFM and google that but no luck. 我一直在尝试RTFM并谷歌,但没有运气。

I am trying to make a silly function in R that takes a vector as argument, loops through it with a for loop and does a very simple addition to each component. 我试图在R中创建一个愚蠢的函数,它将一个向量作为参数,使用for循环遍历它,并对每个组件进行非常简单的添加。

func1 <- function(vector) {
  vr <- c() ### an empty vector 

  for (i in 1:length(vector)) { 
    vr <- vector[i]+i
  }
}

To me this looks correct, but I am always getting a NULL vector. 对我来说,这看起来是正确的,但我总是得到一个NULL向量。 Why? 为什么?

You could write that much more efficiently like this: 你可以像这样写得更有效率:

func1 <- function(vector){
    vector + seq_along(vector)
}

This way you are taking advantage of vector addition. 这样你就可以利用矢量加法了。

For the sake of completeness, let's benchmark these two solutions. 为了完整起见,让我们对这两个解决方案进行基准测试。 Here is the general loop solution: 这是一般循环解决方案:

func2 <- function(vector) {
    vr <- c() ### an empty vector 

    for (i in 1:length(vector)) { 
        vr[i] <- vector[i]+i
    }
    vr
}

As a step up, there is also the in-place solution 作为一个进步,还有就地解决方案

func3 <- function(vector) {    
    for (i in 1:length(vector)) { 
        vector[i] <- vector[i]+i
    }
    vector
}

Using microbenchmark we can see that the vectorized solution is by far the most efficient. 使用微microbenchmark我们可以看到矢量化解决方案是迄今为止最有效的。

vec <- sample(100000, 10000)

library(microbenchmark)
microbenchmark(func1(vec), func3(vec), func2(vec))

Unit: microseconds
       expr       min        lq         mean    median       uq         max neval cld
 func1(vec)    29.998    36.984     44.78312    42.736    44.38     399.006   100  a 
 func3(vec) 12845.823 13666.432  14452.02863 14060.712 14708.53   25025.950   100  a 
 func2(vec) 84898.055 87354.750 110046.26659 88634.566 91193.38 1042819.269   100   b

Your code is close but has two problems. 您的代码很接近但有两个问题。 First, unless specified with a return() call, functions in R return the last expression. 首先,除非使用return()调用指定,否则R中的函数将返回最后一个表达式。 In your function this is the for loop itself. 在你的函数中,这是for循环本身。 But the for loop expression returns nothing in and of itself. 但for循环表达式本身并不返回任何内容。

Second, the last line doesn't index on vr , so you are overwriting it completely with the last result in the loop. 其次,最后一行不在vr索引,所以你用循环中的最后一个结果完全覆盖它。

Thus, this code will (I think) do what you want. 因此,这段代码(我认为)会做你想要的。 But agreed with the other answer that there are easier ways to do this. 但同意其他答案,有更简单的方法来做到这一点。

func1 <- function(vector) {
  vr <- c() ### an empty vector 

  for (i in 1:length(vector)) { 
    vr[i] <- vector[i]+i
  }
  vr
}

This gives this output: 这给出了这个输出:

> func1(c(1,2))
[1] 2 4

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

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