mardi 5 janvier 2021

Create column which tells source of number between the first two columns

I have a data frame which has three columns:

df <- structure(list(lowage = c(45, 15, 9, 51, 22, 45, 4, 4, 9, 25), 
    highage = c(50, 21, 14, 60, 24, 50, 8, 8, 14, 30)), .Names = c("lowage", 
"highage"), row.names = c(NA, 10L), class = "data.frame")

df$random_number <- apply(df, 1, function(x) sample(seq(x[1], x[2]), 1))

I want to create a fourth column that tells us the source of the where the random_number comes from. So for example, in the first row, the column lowage = 45 and highage = 46. Say, the random number generated is 46 (for example). I'd like to create a fourth column where it says as a label 'highage' since it comes from the highage column. And so on...

If the solution can be in dplyr, that would be great!

Aucun commentaire:

Enregistrer un commentaire