Loop vectorization

I am creating some artificial data. I need to create a household identifier (H_ID) and a personal identifier (P_ID, in each house).

I found a way to create an H_ID in a vectorized way.

N <- 50

### Household ID
# loop-for
set.seed(20110224)
H_ID <- vector("integer", N)
H_ID[1] <- 1
for (i in 2:N) if (runif(1) < .5) H_ID[i] <- H_ID[i-1]+1 else H_ID[i] <- H_ID[i-1]
print(H_ID)

# vectorised form
set.seed(20110224)
r <- c(0, runif(N-1))
H_ID <- cumsum(r < .5)
print(H_ID)

But I can't figure out how to create a P_ID in a vectorized way.

### Person ID
# loop-for
P_ID <- vector("integer", N)
P_ID[1] <- 1
for (i in 2:N) if (H_ID[i] > H_ID[i-1]) P_ID[i] <- 1 else P_ID[i] <- P_ID[i-1]+1
print(cbind(H_ID, P_ID))

# vectorised form
# ???
+2
source share
5 answers

Inspired by Martin Morgan 's decision to a closely related issue, here is a really vectorized way to generate P_IDusing functions cummax. As soon as you notice that P_IDis closely linked to cumsumfrom !(r < 0.5):

set.seed(1)
N <- 10
r <- c(0, runif(N-1))
H_ID <- cumsum(r < .5)
r_ <- r >= .5 # flip the coins that generated H_ID.
z <- cumsum(r_)  # this is almost P_ID; just need to subtract the right amount...
# ... and the right amount to subtract is obtained via cummax
P_ID <- 1 + z - cummax( z * (!r_) )
> cbind(H_ID, P_ID)
      H_ID P_ID
 [1,]    1    1
 [2,]    1    2
 [3,]    2    1
 [4,]    3    1
 [5,]    3    2
 [6,]    3    3
 [7,]    3    4
 [8,]    4    1
 [9,]    5    1
[10,]    5    2

I have not done detailed time tests, but it is probably evil, because these are all internal, vectorized functions

+1
source

:

P_ID <- ave(rep(1, N), H_ID, FUN=cumsum)

ave () .

+4
P_ID <- unname(unlist(tapply(H_ID, H_ID, function(x)c(1:length(x)))))
+2

seq_along() - . H_ID , :

> head(split(H_ID, H_ID))
$`1`
[1] 1 1

$`2`
[1] 2

$`3`
[1] 3 3 3 3
....

Q lapply() seq_along() ; seq_along() 1:length(foo). , names:

> unname(unlist(lapply(split(H_ID, H_ID), seq_along)))
 [1] 1 2 1 1 2 3 4 1 1 2 3 1 1 1 1 1 2 3 4 5 1 2 3 4 1 1 2 1 2 1
[31] 1 2 1 2 3 4 1 2 1 2 1 2 1 1 2 1 2 1 2 3
0

. :

cbind(H_ID,   unlist( sapply(table(H_ID), seq) ) )

- table() - ed seq(), 1.

0

All Articles