Home > Software design >  Implement FOR Loop with length function in single command in R
Implement FOR Loop with length function in single command in R

Time:03-02

Is there a quick way to implement the following code in R, in a single command

vec = 0
for(i in 1:3){
 vec = vec   length((2^(i-1)):(2^i-1))
}
vec
[1] 7

Somewhere I've seen that we can use apply or apply functions to do that, but I cannot find it somewhere.

CodePudding user response:

Here's a oneliner that does the same.

sum(sapply(1:3, function(i) length((2^(i-1)):(2^i-1))))

CodePudding user response:

You can use this code:

vec = 0
sum(sapply(1:3,function(i) {vec   length((2^(i-1)):(2^i-1))}))
  •  Tags:  
  • r
  • Related