lundi 24 juin 2019

R : sample function repeats same value within ifelse

I have the following dataframe:

structure(list(Store = c("vpm", "vpm", 
"vpm"), Date = structure(c(18042, 18042, 18042), class = "Date"), 
    UniqueImageId = c("vp3_523", "vp3_668", "vp3_523"), EntryTime = structure(c(1558835514, 
    1558834942, 1558835523), class = c("POSIXct", "POSIXt")), 
    ExitTime = structure(c(1558838793, 1558838793, 1558839824
    ), class = c("POSIXct", "POSIXt")), Duration = c(3279, 3851, 
    4301), Age = c(35L, 35L, 35L), EntryPoint = c("Entry2Side", 
    "Entry2Side", "Entry2Side"), ExitPoint = c("Exit2Side", "Exit2Side", 
    "Exit2Side"), AgeNew = c("15_20", "25_32", "15_20"), GenderNew = c("Female", 
    "Male", "Female")), row.names = 4:6, class = c("data.table", 
"data.frame"))

I am trying to populate a random number for the column AgeNew and I am using sample function with ifelse condition.

I tried the following

d$AgeNew <- ifelse(d$AgeNew == "0_2",   sample(0:2,  1,replace = TRUE), 
            ifelse(d$AgeNew == "15_20", sample(15:20,1,replace = TRUE), 
            ifelse(d$AgeNew == "25_32", sample(25:36,1,replace = TRUE), 
            ifelse(d$AgeNew == "38_43", sample(36:43,1,replace = TRUE), 
            ifelse(d$AgeNew == "4_6",   sample(4:6,  1,replace = TRUE), 
            ifelse(d$AgeNew == "48_53", sample(48:53,1,replace = TRUE), 
            ifelse(d$AgeNew == "60_Inf",sample(60:65,1,replace = TRUE), 
                                        sample(8:13, 1,replace = TRUE))))))))

But I am getting the same value getting repeated. For example, for the age group 0_2 I have only 2 populated. I tried using set.seed

set.seed(123)

and then running the ifelse still it repeats the same value.

Aucun commentaire:

Enregistrer un commentaire