Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

Avoid for loop when loop has an increment

$
0
0

In R, I try systematically to avoid "for" loops and use lapply() family instead.
But how to do so when an iteration contains an increment step ?

For example : is it possible to obtain the same result as below with a lapply approach ?

a <- c()
b <- c()
set.seed(1L) # required for reproducible data
for (i in 1:10){
  a <- c(a, sample(c(0,1), 1))
  b <- c(b, (paste(a, collapse = "-")))
}
data.frame(a, b)


> data.frame(a, b)
>    a                   b
> 1  0                   0
> 2  1                 0-1
> 3  0               0-1-0
> 4  0             0-1-0-0
> 5  1           0-1-0-0-1
> 6  0         0-1-0-0-1-0
> 7  0       0-1-0-0-1-0-0
> 8  0     0-1-0-0-1-0-0-0
> 9  1   0-1-0-0-1-0-0-0-1
> 10 1 0-1-0-0-1-0-0-0-1-1

EDIT My question was very badly redacted. The below new example is much more illustrative : is it anyway to use lapply family if each iteration is calculated from the previous one ?

a <- c()
b <- c()
for (i in 1:10){
  a <- c(a, sample(c(0,1), 1))
  b <- c(b, (paste(a, collapse = "-")))
}
data.frame(a, b)

> data.frame(a, b)
   a                   b
1  0                   0
2  1                 0-1
3  0               0-1-0
4  1             0-1-0-1
5  1           0-1-0-1-1
6  1         0-1-0-1-1-1
7  1       0-1-0-1-1-1-1
8  0     0-1-0-1-1-1-1-0
9  1   0-1-0-1-1-1-1-0-1
10 1 0-1-0-1-1-1-1-0-1-1

Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>