【问题标题】:replacing id column with sequence of number using R [duplicate]使用 R [重复] 用数字序列替换 id 列
【发布时间】:2022-01-22 19:28:25
【问题描述】:

我有一个这样的df

structure(list(id = c(1162, 1162, 1162, 1388, 1388, 1388, 1492, 
1492, 1492), chapter = c(1, 2, 1, 3, 4, 5, 2, 1, 3)), class = "data.frame", row.names = c(NA, 
-9L))

我想用数字替换 id 列值,使其看起来像这样

structure(list(id2 = c(1, 1, 1, 2, 2, 2, 3, 3, 3), chapter = c(1, 
2, 1, 3, 4, 5, 2, 1, 3)), class = "data.frame", row.names = c(NA, 
-9L))

【问题讨论】:

    标签: r


    【解决方案1】:

    cumsumdifferences。

    df1 <- transform(df1, id=c(1, cumsum(diff(df1$id) > 0) + 1))
    df1
    #   id chapter
    # 1  1       1
    # 2  1       2
    # 3  1       1
    # 4  2       3
    # 5  2       4
    # 6  2       5
    # 7  3       2
    # 8  3       1
    # 9  3       3
    

    【讨论】:

      【解决方案2】:

      试试这个:

      df$id <- as.numeric(as.factor(df$id))
      

      【讨论】:

        猜你喜欢
        • 2013-02-25
        • 2021-11-29
        • 2018-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-26
        • 1970-01-01
        • 2017-02-18
        相关资源
        最近更新 更多