2016-03-07 43 views
0

我需要從數據框中兩個變量的組合創建唯一標識符。考慮以下數據幀:從兩個變量的可互換組合創建唯一標識符

df <- data.frame(col1 = c("a", "a", "b", "c"), col2 = c("c", "b", "c", "a"), id = c(1,2,3,1) 

變量「id」不在數據集中;那是我想創造的那個。基本上,我希望可以互換地處理變量col1和col2的每個組合,例如, c(「a」,「c」)的組合與c(「c」,「a」)相同。

+0

喜歡的東西在這裏可能會有所幫助 - http://stackoverflow.com/questions/25297812/pair-wise-duplicate-removal-from-dataframe/ 25298863 – thelatemail

回答

2

你可以這樣做:

labels <- apply(df[, c("col1", "col2")], 1, sort) 
df$id <- as.numeric(factor(apply(labels, 2, function(x) paste(x, collapse="")))) 
+0

工程就像一個魅力:) thx – crubba

2

一個更復雜,但更快的運行版本比遍歷每一行。

sel <- c("col1","col2") 
df[sel] <- lapply(df[sel], as.character) 

as.numeric(factor(apply(df[1:2], 1, function(x) toString(sort(x))))) 
#[1] 2 1 3 2 

as.numeric(interaction(list(do.call(pmin,df[1:2]),do.call(pmax,df[1:2])),drop=TRUE)) 
#[1] 2 1 3 2 

標杆上1M行:

df2 <- df[rep(1:4, each=2.5e5),] 

system.time(as.numeric(factor(apply(df2[1:2], 1, function(x) toString(sort(x)))))) 
# user system elapsed 
# 69.21 0.08 69.41 

system.time(as.numeric(interaction(list(do.call(pmin,df2[1:2]),do.call(pmax,df2[1:2])),drop=TRUE))) 
# user system elapsed 
# 0.88 0.03 0.91 
+0

速度是一個問題的酷解決方案(但在這種情況下不適用於我)。謝謝 – crubba