bvowe
bvowe

Reputation: 3384

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

Upvotes: 2

Views: 767

Answers (4)

Todd D
Todd D

Reputation: 278

Here is another dplyr solution that uses rowwise():

     library(dplyr)
      data1 <- data.frame("Cat" = c(8,4,3,7,6,2,2),
                         "Dog"=c(4,7,10,5,8,1,9),
                         "Want"=NA)
      
      data1 <- data1 %>% rowwise() %>% 
               mutate( Try = if_else(Dog > Cat, (Dog - Cat) * (1-runif(1, 0.5, 0.9)), -99))

Upvotes: 0

akrun
akrun

Reputation: 887311

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))

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101848

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))

Upvotes: 1

Chris Ruehlemann
Chris Ruehlemann

Reputation: 21410

You can do this by sampleing:

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

Upvotes: 1

Related Questions