I'm trying to create a variable position that has a max constraint of n securities in the portfolio at a time. Let's say a max of 5 positions at the time, which can be randomly selected after keeping the previous positions. The selection criteria is when escore == 5, I have a buy signal. Otherwise, it's a sell signal. Below is a reproduced data example.
k <- 20
df <- tibble(v1 = rep(letters[1:k], each = 10),
date = rep(seq(as.Date('2018-01-01'),by='months',length=10), k),
escore = sample(5, k*10, replace = T))
df <- df %>% mutate(init = ifelse(date == "2018-01-01" & escore == 5, 1, 0),
sell = ifelse(escore <5, 1, 0),
buy = ifelse(escore ==5, 1, 0))
max <- 4
This is the initial positions

If there is a sell signal on 2 of these securities in the next period, then the "position" variable becomes 0 and randomly add 2 other securities out of the qualified basket (when escore == 5) for that period. v1 indicates the names of securities.
Any help would be appreciated!