3

I have the below df

    var1 var2 Freq
1    a    b   10
2    b    a    5
3    b    d   10

created from

help <- data.frame(var1 = c("a", "b", "b"), var2 = c("b", "a", "d"), Freq = c(10, 5, 10))

ab correlation is the same as ba, and I am hoping to combine them into one row to look like

   var1 var2 Freq
1    a    b   15
2    b    d   10

any thoughts?

1
  • By using stringsAsFactors=FALSE, you can change var1=pmin(var1,var2) and var2=pmax(var1,var2), after which aggregation should be straightforward. Commented Oct 17, 2014 at 20:45

2 Answers 2

2

Here's one way:

setNames(aggregate(help$Freq, as.data.frame(t(apply(help[-3], 1, sort))), sum), 
         names(help))

#   var1 var2 Freq
# 1    a    b   15
# 2    b    d   10
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, Sven. Can you explain what the help[-3] means?
@bpace The command help[-3] is an example of negative indexing. It returns all columns of help except the third one.
0

In base R :

do.call(rbind,
by(dat,rowSums(sapply(dat[,c("var1","var2")],as.integer)),
   function(x)data.frame(x[1,c("var1","var2")],
                         Freq= sum(x[,"Freq"]))))

  var1 var2 Freq
3    a    b   15
5    b    d   10

I create first a grouping variable by summing the integer representation of your columns. Then performing the sum of frequencies by group. Finally bind the result to get a new data.frame.

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.