I am trying to generate random numbers within a tibble where different categories of item are distributed differently. I'm not having much luck. Here's the code and the error it produces:
library(dplyr)
letters <- tibble(letter = c(rep("A", 5), rep("B", 5), rep("C", 5) ))
letters %>%
rowwise() %>%
mutate(Proj = case_when(
letter == "A" ~ rpois(1, lambda = .7746),
letter == "B" ~ rnbinom(1, size = 3.3848, mu = 1.2),
letter == "C" ~ rpois(1, lambda = .5057)
))
#> Error in `mutate()`:
#> ! Problem while computing `Proj = case_when(...)`.
#> ℹ The error occurred in row 1.
#> Caused by error in `` names(message) <- `*vtmp*` ``:
#> ! 'names' attribute [1] must be the same length as the vector [0]
Interestingly, the code works just fine if I use continuous distributions instead of discrete distributions.
library(dplyr)
letters <- tibble(letter = c(rep("A", 5), rep("B", 5), rep("C", 5) ))
letters %>%
rowwise() %>%
mutate(Proj = case_when(
letter == "A" ~ rweibull(1, shape = 2.3487, scale = 8.174),
letter == "B" ~ rexp(1, rate = .0442),
letter == "C" ~ rnorm(1, mean = 0, sd = 1)
))
#> # A tibble: 15 × 2
#> # Rowwise:
#> letter Proj
#> <chr> <dbl>
#> 1 A 9.82
#> 2 A 7.72
#> 3 A 12.9
#> 4 A 7.81
#> 5 A 6.44
#> 6 B 10.4
#> 7 B 3.14
#> 8 B 1.48
#> 9 B 28.7
#> 10 B 11.0
#> 11 C -0.378
#> 12 C -0.340
#> 13 C 1.81
#> 14 C 1.03
#> 15 C -0.679
Created on 2022-07-29 by the reprex package (v2.0.1)
What's going on here?
Aucun commentaire:
Enregistrer un commentaire