从两个变量的可互换组合创建唯一标识符



我需要从数据框中两个变量的组合创建一个唯一标识符。请考虑以下数据框:

 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") 相同)。

你可以做:

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

一个比遍历每一行更复杂但运行更快的版本。

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 

最新更新