Reputation: 93
I am converting between two programs that use different logic structures. The original program uses conditional statements to define probabilities. For example, if Condition_A = (1 OR 2 OR 3) AND Condition_B = (X OR Y) THEN Probability = 0.5. The table looks like this:
Condition_A Condition_B Probability
1, 2, 3 X, Y 0.5
The new program requires a separate line for each combination, like this:
Condition_A Condition_B Probability
1 X 0.5
2 X 0.5
3 X 0.5
1 Y 0.5
2 Y 0.5
3 Y 0.5
I have the top table and need to convert it into the bottom table. I am looking to write an R script to automate the conversion for ~2,000 conditional statements. I am totally stumped so I don't have any code to show what I have tried. TIA
Upvotes: 2
Views: 46
Reputation: 8811
library(tidyverse)
df <-
tibble(
condition_A = c("1,2,3"),
condition_B = c("X,Y"),
probability = .5
)
df %>%
separate_rows(condition_A) %>%
separate_rows(condition_B)
# A tibble: 6 x 3
condition_A condition_B probability
<chr> <chr> <dbl>
1 1 X 0.5
2 1 Y 0.5
3 2 X 0.5
4 2 Y 0.5
5 3 X 0.5
6 3 Y 0.5
Upvotes: 2
Reputation: 15123
By separate_rows
df <- tibble::tribble(
~Condition_A, ~Condition_B, ~Probability,
"1, 2, 3", "X, Y", 0.5
)
df %>%
separate_rows(., Condition_A) %>%
separate_rows(., Condition_B)
Condition_A Condition_B Probability
<chr> <chr> <dbl>
1 1 X 0.5
2 1 Y 0.5
3 2 X 0.5
4 2 Y 0.5
5 3 X 0.5
6 3 Y 0.5
Upvotes: 2