2

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

2

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

Libraries

library(tidyverse)

Data

df <-
  tibble(
    condition_A = c("1,2,3"),
    condition_B = c("X,Y"),
    probability = .5
    
  )

Code

df %>% 
  separate_rows(condition_A) %>% 
  separate_rows(condition_B)

Output

# 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.