简体   繁体   English

R中的数据框列的组合

[英]Combination of dataframe columns in R

I have a data frame that looks like the following: 我有一个数据框架,如下所示:

df <-
Date  P1 P2 P3 P4
1/31  5  3  4  5 
2/28  2  3  7  8 
3/31  5  6  7  8 

I would like to take all combinations, by date, of columns P1...P4, taken 2 at a time -- 4C2. 我想按日期对列P1 ... P4进行所有组合,一次取2 – 4C2。 The result would be a list that contains the resultant data frames and will ideally look like this: 结果将是一个包含结果数据帧的列表,理想情况下将如下所示:

[[1]]
Date  P1 P2
1/31  5  3  
2/28  2  3  
3/31  5  6 

[[2]]
Date  P1 P3 
1/31  5  4   
2/28  2  7   
3/31  5  7  

.
.
.  

I'm trying to go about this using the combn() function. 我正在尝试使用combn()函数。 I can accomplish the combination by doing 我可以通过完成组合

combn(names(df),2,simplify=FALSE) 

but this gives me neither the dates nor the values in the result. 但这给了我日期和结果值。 How should I go about this task? 我应该如何完成这项任务?

Try this 尝试这个

ind <- which(names(df)=="Date") # find the index of Date column
combn(ncol(df)-1, 2, function(a) cbind(df[ind], df[-ind][a]), simplify = F)

Using lapply you could do 使用lapply你可以做

split_vec = combn(names(df)[-1], 2)

lapply(1:ncol(split_vec), function(x) select(df, "Date", split_vec[, x]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM