简体   繁体   中英

R Conditional IfElse With Random Values

data1 = data.frame("Cat" = c(8,4,3,7),
                   "Dog"=c(4,7,10,5),
                   "Want"=NA)

data1$Try = ifelse(data1$Dog > data1$Cat, (data1$Dog - data1$Cat) * (1-runif(1, 0.5, 0.9)), -99)

I wish to create "Want" with this rule: if Dog > Cat, "Want" = (Dog - Cat) * (1-runif(1, 0.5, 0.9))

However when I do this with "Try" it uses the same random 'runif' value, however, for each time Dog > Cat I wish to generate a new value from 'runif' and not use the same one each time.

data1 = data.frame("Cat" = c(8,4,3,7),
                   "Dog"=c(4,7,10,5),
                   "Want"=NA)

data1 <- within(data1, Want2 <- ifelse(Dog-Cat>0,(Dog-Cat)*(1-runif(1, 0.5, 0.9)),-99))
data1$Dif = (data1$Dog - data1$Cat)/data1$Want2

I wish for this ratio to be different each time Dog > Cat

You can do this by sample ing:

data1$Want = ifelse(data1$Dog > data1$Cat, 
                (data1$Dog - data1$Cat) * (1-runif(sample(1:10,1, replace = T), 0.5, 0.9)), -99)

You can try ifelse like below

data1 <- within(data1, Want <- ifelse(Dog-Cat>0,(Dog-Cat)*(1-runif(nrow(data1), 0.5, 0.9)),-99))

We can use case_when

library(dplyr)
data1 %>% 
   mutate(Want = case_when(Dog > Cat ~ (Dog - Cat)* 
      (1 - runif(sample(1:10,1, replace = T), 0.5, 0.9)), TRUE ~ -99))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM