Skip to content

Instantly share code, notes, and snippets.

@korkridake
Created November 12, 2018 17:54
Show Gist options
  • Save korkridake/d606026c621863ceb345f9c202561059 to your computer and use it in GitHub Desktop.
Save korkridake/d606026c621863ceb345f9c202561059 to your computer and use it in GitHub Desktop.
vector_analyse function to increase the number of children by 1
# As inputs your function should take a vector of 0s and 1s; Every time you see a sequence of 1s in the data you need to increase the number of children by 1; Be careful with the two subsequent sequences of 1s, where the difference between them is less than 5 (i.e. when there are less than 5 0s in between them, then it is the same child and not a new child); To help you social planner provides some examples of what your function should return:
#Input: c(1,1,1,1,0,0,0,0)
#Output: 1 1 1 1 1 1 1 1
#Input: c(0,0,0,0,1,1,1,1,0,0,0,0,0,1,1,1)
#Output: 0 0 0 0 1 1 1 1 1 1 1 1 1 2 2 2
#Input: c(0,0,0,0,1,1,1,1,0,0,1,1,0,0,0,1,1,0,0,0,0,1,1,0,0,0,0,0,1)
#Output: 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2
vector_analyse <- function(sample_vector){
# ----------------------------------------------------------------------------
# Signature: vector --> vector
# Author: Korkrid Akepanidtaworn
# Description: Given a sample vector of 0s and 1s, return a sequence of 1s in
# the data you need to increase the number of children by 1 (when there are less
# 5 0s in between them, then it is the same child and not a new child)
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Run Length Encoding gives a list of length and values
# ----------------------------------------------------------------------------
rle_object <- rle(sample_vector)
x <- rle_object$lengths # original length
y <- rle_object$values # original values
z <- which(y == 1) # index of 1 in vector y
if (length(z) == 1){
invisible()
} else{
for (i in 2:length(z)){
if (x[z[i]-1] >= 5){
y[z[i]] = y[z[i]]
} else {
y[z[i]] = y[z[i]] - 1
}
}
}
y_cumsum = cumsum(y)
rle_object$values <- y_cumsum
new_vector = inverse.rle(rle_object)
return(new_vector)
}
vector_analyse(c(1,1,1,1,0,0,0,0))
vector_analyse(c(0,0,0,0,1,1,1,1,0,0,0,0,0,1,1,1))
vector_analyse(c(0,0,0,0,1,1,1,1,0,0,1,1,0,0,0,1,1,0,0,0,0,1,1,0,0,0,0,0,1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment