【问题标题】:Create unique identifier from the interchangeable combination of two variables从两个变量的可互换组合创建唯一标识符
【发布时间】:2019-01-10 16:07:37
【问题描述】:

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

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

【问题讨论】:

标签: r


【解决方案1】:

你可以这样做:

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

【讨论】:

    【解决方案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 
    

    【讨论】:

      猜你喜欢
      • 2019-08-05
      • 2011-08-25
      • 1970-01-01
      • 1970-01-01
      • 2021-09-14
      • 1970-01-01
      • 2021-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多