![](/img/trans.png)
[英]How to create histograms for each unique combination of levels from two factors?
[英]Create unique identifier from the interchangeable combination of two variables
我需要根据数据帧中两个变量的组合来创建唯一标识符。 考虑以下数据帧:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.