Reputation: 2513
I have this data
data <- c("h", "H", "homme", "masculin", "f")
I want to repeat each values based on random values in an interval range
What I Tried :
dummy <- rep(data, ceiling(runif (1, 1, 3)))
sort(dummy)
My results :
"f" "f" "h" "h" "H" "H" "homme" "homme" "masculin" "masculin"
What I expected : each value can be repeat randomly in a range
I can expect : 2 "f", 3 "homme", 1 "masculin"
or
I can expect 1 "f", 1 "homme", 3 "masculin"
...
Upvotes: 0
Views: 67
Reputation: 3755
Another approach...
reptime <- sapply(1:length(data),function(x)
x <- ceiling(runif(1, 0, 3)) );
dummy <- rep(data , reptime );
sort(dummy)
Upvotes: 1
Reputation: 51582
One way to do this is to use mapply
to rep
vector data
, sample(3, 3)
times.
NOTE That it will give you warning
Warning message: In mapply(rep, data, sample(3, 3)) :
longer argument not a multiple of length of shorter
However, It shouldn't worry you because it will recycle the sample
vector in which case all the recycled values will again be in your predefined range, thus satisfying your conditions, i.e.
unname(unlist(mapply(rep, data, sample(3, 3))))
#[1] "h" "H" "H" "H" "homme" "homme" "masculin" "f" "f" "f"
unname(unlist(mapply(rep, data, sample(3, 3))))
#[1] "h" "H" "H" "homme" "homme" "homme" "masculin" "f" "f"
unname(unlist(mapply(rep, data, sample(3, 3))))
#[1] "h" "h" "H" "H" "H" "homme" "masculin" "masculin" "f" "f" "f"
Upvotes: 1