2017-08-31 53 views
1

我有data.table 4列以上。前三個是獲取關於一個獨特個體的數據所必需的。從列的組合中獲取唯一的哈希值

c1 c2 c3 c4 
a c e other_data 
a c e other_data 
a c f other_data 
a c f other_data 
a d f other_data 
b d g other_data 

# (c1 = "a" AND c2 = "c" AND c3 = "e") => one individual 
# (c1 = "a" AND c2 = "c" AND c3 = "f") => another individual 

我想計算另一列這將標誌着每一個人:

c1 c2 c3 c4   unique_individual_id 
a c e other_data 1 
a c e other_data 1 
a c f other_data 2 
a c f other_data 2 
a d f other_data 3 
b d g other_data 4 

我想獲得一個唯一的哈希出3列的內容。

我該怎麼做代碼?

回答

5
as.numeric(as.factor(with(df, paste(c1, c2, c3)))) 
#[1] 1 1 2 2 3 4 
+1

所有三個答案的工作,但是這一次是最快的,根據'microbenchmark' –

+1

類似,'c(unclass(as.factor(Reduce(paste,dat [-4]))))'。最後的'c'去掉未使用的關卡屬性。 – lmo

3

我們可以使用interaction

df1$unique_individual_id <- as.integer(do.call(interaction, c(df1[-4], drop = TRUE))) 
df1$unique_individual_id 
#[1] 1 1 2 2 3 4 
2

或者創建唯一索引,可以粘貼感興趣的值(每行,你在,2列1的值粘貼在一起,和3 ),轉換爲因素,然後爲整數(這將返回一個唯一的ID NUM爲您的組合。

df <- data.frame(c("a", "a", "b", "c", "c", "d", "d"), 
       c("a", "a", "b", "c", "d", "e", "e"), 
       c("c", "c", "d", "d", "e", "e", "e")) 
df$ID <- as.numeric(as.factor(sapply(1:nrow(df), (function(i) {paste(df[i, 1:3], collapse = "")}))))