I'm quite new to R and I'd like to ask if it's possible to use sample()
inside of case_when()
when generating a synthetic sample.
Here's an example that hopefully conveys - even though it fails - what I have in mind:
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"),
length(which(type == "car")),
replace = TRUE,
prob = c(2/3, 1/3)),
type == "truck" ~ sample(c("petrol", "diesel"),
length(which(type == "truck")),
replace = TRUE,
prob = c(0.1, 0.9)),
TRUE ~ NA_character_
)
)
This doesn't run through. Is the code wrong, or can you think of different approaches to achieve this?