【问题标题】:how to choose a row when the row number of that row is equal to the value of the other column with duplicates in R?当该行的行号等于R中具有重复项的另一列的值时,如何选择一行?
【发布时间】:2021-06-20 17:57:24
【问题描述】:

我有一个数据框如下-

df <- cbind(c(1,1,1,2,2,2,3,3,3,3), c(6,12,18,3,9,12,4,8,12,16),c(3,3,3,2,2,2,4,4,4,4))
colnames(df) <- c("ID","value","index")

我想得到以下结果-

df1 <- cbind(c(1,2,3), c(18,9,16),c(3,2,4))

所以我基本上想提取(对于每个 ID)行号等于该 ID 的索引的行。例如,第 3 行为 ID 1,第 2 行为 ID 2,第 4 行为 ID 4。

我尝试了以下代码

df1 <- df%>%group_by(ID)%>%filter(index==index)

但它不起作用。请帮我解决这个问题。

【问题讨论】:

    标签: r row row-number


    【解决方案1】:

    使用slice 为每个ID 选择index 行。

    library(dplyr)
    df %>% group_by(ID) %>% slice(first(index)) %>% ungroup
    
    #     ID value index
    #  <dbl> <dbl> <dbl>
    #1     1    18     3
    #2     2     9     2
    #3     3    16     4
    

    这可以写成 data.table 和基数 R 为:

    library(data.table)
    setDT(df)[, .SD[first(index)], ID]
    
    #Base R
    subset(df, index == ave(value, ID, FUN = seq_along))
    

    数据

    df <- data.frame(ID = c(1,1,1,2,2,2,3,3,3,3), 
                     value = c(6,12,18,3,9,12,4,8,12,16),
                     index = c(3,3,3,2,2,2,4,4,4,4))
    

    【讨论】:

      【解决方案2】:

      只是添加到 Ronak Shah 的答案中,我想执行您想要的操作的简单代码之一如下:

      library(dplyr)
      df <- 
          data.frame(ID = c(1,1,1,2,2,2,3,3,3,3), value = c(6,12,18,3,9,12,4,8,12,16), index = c(3,3,3,2,2,2,4,4,4,4))
      
      df %>% group_by(ID) %>% filter(row_number() == index) %>% ungroup
      

      【讨论】:

      • 您的回答也很有效...非常感谢
      猜你喜欢
      • 2015-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-18
      相关资源
      最近更新 更多