Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
820 views
in Technique[技术] by (71.8m points)

r - Pairwise unique combinations ignoring the direction

I want to aggregate a certain value in a data.frame based on a common character in R. The Problem is that I am not interested in different directions of the pairwise combination. So for instance

d = data.frame( x = LETTERS[1:5], y = LETTERS[5:1] )

  x y
1 A E
2 B D
3 C C
4 D B
5 E A

The combination would be then calculated like this:

d$z <- paste0(d$x,d$y,sep="_")

The problem is that i am not interested in pairwise differences. So A_E should be the same as E_A in this simple example.

Is there a clever short solution to paste them? I am currently thinking about sorting each one before combining them into a vector.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One option is to use pmin and pmax:

transform(d, z = paste(pmin(x,y), pmax(x,y), sep="_"))
#  x y   z
#1 A E A_E
#2 B D B_D
#3 C C C_C
#4 D B B_D
#5 E A A_E

Note that you might need to convert x and y to character if they are factors.


d <- data.frame( x = LETTERS[1:5], y = LETTERS[5:1], stringsAsFactors = FALSE)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...