Plantekös
Plantekös

Reputation: 33

Combinations in the right order

I am dealing with combinations of variables. In my model the combination (A,B) would be similar to (B,A). I would like to reshape my data in order to get similar combinations in the same order.

I try to used the duplicated function and to work with the paste function but I do not sort out the issue.

This is my first table :

df <- data.frame(V1=c("A","A","A","B","B","B"),
                 V2=c("B","C","D","A","D","A"))

This what I would like to obtain :

df2 <- data.frame(V1=c("A","A","A","B","B","B"),
                  V2=c("B","C","D","A","D","A"),
                  Test=c("OK","OK","OK","FALSE","OK","FALSE"),
                  V1b=c("A","A","A","A","B","A"),
                  V2b=c("B","C","D","B","D","B"))

Upvotes: 1

Views: 54

Answers (2)

tmfmnk
tmfmnk

Reputation: 39858

With dplyr, you can do:

df %>%
 mutate(V1b = pmin(V1, V2), 
        V2b = pmax(V1, V2),
        Test = paste0(V1, V2) != paste0(V1b, V2b))

  V1 V2 V1b V2b  Test
1  A  B   A   B FALSE
2  A  C   A   C FALSE
3  A  D   A   D FALSE
4  B  A   A   B  TRUE
5  B  D   B   D FALSE
6  B  A   A   B  TRUE

Upvotes: 1

cicero
cicero

Reputation: 528

Assuming the "right order" is the alphabetical order, you can use

alphabetical <- function(x,y){x < y}

which return true when x,y is sorted alphabetically and false otherwise.

EDIT : here is a working solution :


df_sorted <- df %>% rowwise() %>% mutate(Test = alphabetical(as.character(V1),as.character(V2))) %>% 
                 mutate(V1b = if (Test) {
                  as.character(V1)
                } else {
                  as.character(V2)
                }) %>% 
                mutate(V2b = if (Test) {
                  as.character(V2)
                } else {
                  as.character(V1)
                })

Upvotes: 2

Related Questions