【问题标题】:How to index columns uniquely? [duplicate]如何唯一索引列? [复制]
【发布时间】:2017-08-31 07:34:03
【问题描述】:

试图找到类似的帖子,但找不到。

我在数据表中有一个如下所示的列 ->

x,x,x,x,y,y,y,c,c,c

我想在单独的列中建立索引,这样 ->

1,1,1,1,2,2,2,3,3,3

怎么做?

【问题讨论】:

标签: r


【解决方案1】:

我会选择这个,它具有处理数据框和数据表的优势,(也许还有 tibbles,idk)。索引号是从col 代码的第一次出现获得的,输出索引号不依赖于相邻行的col 代码(因此,如果col 变为x,x,x,x,y,y,y,x,x,x,则所有x 获取索引2) .

> dt <- data.table(col = c("x", "x", "x", "x", "y", "y", "y", "c", "c", "c")) 
> dt$index = as.numeric(factor(dt$col,levels=unique(dt$col)))
> dt
    col index
 1:   x     1
 2:   x     1
 3:   x     1
 4:   x     1
 5:   y     2
 6:   y     2
 7:   y     2
 8:   c     3
 9:   c     3
10:   c     3

【讨论】:

    【解决方案2】:

    data.table的解决方案:

    library(data.table)
    dt <- data.table(col = c("x", "x", "x", "x", "y", "y", "y", "c", "c", "c")) 
    
    dt[ , idx := .GRP, by = col]
    #     col idx
    #  1:   x   1
    #  2:   x   1
    #  3:   x   1
    #  4:   x   1
    #  5:   y   2
    #  6:   y   2
    #  7:   y   2
    #  8:   c   3
    #  9:   c   3
    # 10:   c   3
    

    base R中的解决方案:

    dat <- data.frame(col = c("x", "x", "x", "x", "y", "y", "y", "c", "c", "c")) 
    
    dat <- transform(dat, idx = match(col, unique(col)))
    #    col idx
    # 1    x   1
    # 2    x   1
    # 3    x   1
    # 4    x   1
    # 5    y   2
    # 6    y   2
    # 7    y   2
    # 8    c   3
    # 9    c   3
    # 10   c   3
    

    【讨论】:

      【解决方案3】:
      dt$index <- cumsum(!duplicated(dt$a))
      dt
      a index
      # 1  x     1
      # 2  x     1
      # 3  x     1
      # 4  x     1
      # 5  y     2
      # 6  y     2
      # 7  y     2
      # 8  c     3
      # 9  c     3
      # 10 c     3
      

      【讨论】:

        猜你喜欢
        • 2019-05-30
        • 1970-01-01
        • 2017-02-19
        • 2016-06-26
        • 2012-03-24
        • 2016-03-22
        • 2021-09-30
        • 1970-01-01
        相关资源
        最近更新 更多