I think this does what you want.
set.seed(seed = 1000)
type <- sample(x = c("car", "truck"),
size = 10,
replace = TRUE,
prob = c(0.6, 0.4))
motor <- ifelse(test = (type == "car"),
yes = sample(x = c("petrol", "diesel"),
size = 1,
prob = c(2/3, 1/3)),
no = sample(x = c("petrol", "diesel"),
size = 1,
prob = c(0.1, 0.9)))
(test <- data.frame(type, motor))
#> type motor
#> 1 car petrol
#> 2 truck diesel
#> 3 car petrol
#> 4 truck diesel
#> 5 car petrol
#> 6 car petrol
#> 7 truck diesel
#> 8 car petrol
#> 9 car petrol
#> 10 car petrol
Created on 2019-03-13 by the reprex package (v0.2.1)
I'm not very comfortable with tidyverse, but I think the problem is in the size argument. I think what mutate does is that it tries to perform your function for each of the elements, but since you are generating more than one, you're having problems. But I'm not sure.
What happens if you try this?
library(tidyverse)
set.seed(1000)
type = sample(c("car", "truck"), 10, replace = TRUE, prob = c(0.6, 0.4))
test <- data.frame(type)
test %>%
mutate(
motor = case_when(
type == "car" ~ sample(c("petrol", "diesel"),
1,
replace = TRUE,
prob = c(2/3, 1/3)),
type == "truck" ~ sample(c("petrol", "diesel"),
1,
replace = TRUE,
prob = c(0.1, 0.9)),
TRUE ~ NA_character_
)
)