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
272 views
in Technique[技术] by (71.8m points)

r - How to obtain all combinations of the columns of a data frame taken by 2?

Suppose I have this data frame:

matrix(c(2,4,3,1,5,7,1,2,3,5,8,2,4,5,1,1,3,6,1,3,4,5,6,1),nrow=6,ncol=4,byrow = TRUE)->X
as.data.frame(X)->X.df

  V1 V2 V3 V4
1  2  4  3  1
2  5  7  1  2
3  3  5  8  2
4  4  5  1  1
5  3  6  1  3
6  4  5  6  1

then I would like to obtain a list of a set of data frames containing all combinations of columns taken by 2, without repetition, and avoiding any column with itself. That means, a list of dataframes with the following headers:

V1,V2
V1,V3
V1,V4
V2,V3
V2,V4
V3,V4

Any idea of how to do this?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
combn(X.df, 2, simplify=FALSE)
[[1]]
  V1 V2
1  2  4
2  5  7
3  3  5
4  4  5
5  3  6
6  4  5

[[2]]
  V1 V3
1  2  3
2  5  1
3  3  8
4  4  1
5  3  1
6  4  6

[[3]]
  V1 V4
1  2  1
2  5  2
3  3  2
4  4  1
5  3  3
6  4  1

[[4]]
  V2 V3
1  4  3
2  7  1
3  5  8
4  5  1
5  6  1
6  5  6

[[5]]
  V2 V4
1  4  1
2  7  2
3  5  2
4  5  1
5  6  3
6  5  1

[[6]]
  V3 V4
1  3  1
2  1  2
3  8  2
4  1  1
5  1  3
6  6  1

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

...