2017-07-29 21 views
0

假設我有一個由組分組成的向量,我正在尋找一種獲得有序的元素選擇而不需要按組重複的方法。 的例子可能會澄清:R:在組內沒有重複的有序選擇

group<-c("a","a","a","b","b","b") 
element<-c(1,2,3,1,2,3) 
data<-data.frame(group,element) 

我想獲得:

group<-c("a","a","a","b","b","b") 
element.x<-(1,1,2,1,1,2) 
element.y<-(2,3,3,2,3,3) 
data<-data.frame(group, element.x,element.y) 

我試圖從dplyr left_join工作,但它給了我所有組合(即(1,2)和(2,1),這不是我正在尋找的)。

require(dplyr) 
data<- data %>% 
left_join(data , by=c("group")) 

可能,我更喜歡東西可以工作,即使變量「元素」是一個字符串。 非常感謝。

回答

0

你可以試試combntapply

group <- c("a","a","a","b","b","b") 
element <- c(1,2,3,1,2,3) 
data <- data.frame(group,element) 

# get per group, all unique combinations 
combinations <- tapply(data$element, data$group, combn, 2) 

# get number of unique combinations per group 
nPerComb <- sapply(combinations, NCOL) 

# bind combinations to a matrix 
elements <- t(do.call(cbind, combinations)) 

# fill dataframe with new information 
data2 <- data.frame(
    group = rep(unique(data$group), nPerComb), 
    element.x = elements[, 1], 
    element.y = elements[, 2] 
) 

這也適用於字符數據,但不適用於因素(這些將被轉換爲數字)。