I make a sample of all values of one column of my data frame in function of other column. To do so, I use tapply
.
ex <- data.frame(
loc = c("1", "1", "2", "2", "2", "3", "3"),
sp = c("a", "b", "b", "c", "d", "a", "d"))
ex
all_sp <- unique(ex[, "sp"])
all_sp <- data.frame(all_sp)
ex$sp_random <- ""
sp_rand <- tapply(ex$sp_random, ex$loc, function(x)
base::sample(all_sp$all_sp, size = length(x), replace = FALSE, prob = NULL))
Now I would like to put the sp_rand
list in the original ex
data frame but I don't know how to it properly.
The only way I found is to reorder ex
column like that :
ex <- ex[order(ex$loc), ]
ex$sp_random <- as.character(unlist(sp_rand))
ex
but order
is quite slow with big data frames.