【问题标题】:How to filter a dataframe by rows without losing the index (or row number)?如何在不丢失索引(或行号)的情况下按行过滤数据框?
【发布时间】:2020-04-13 21:05:56
【问题描述】:

我有一个小数据框 (dt),其中包含来自不同 catboost 运行的二进制标签:

structure(list(old.cat.lab = c(1, 1, 0, 0, 0, 1, 0, 0, 0, 1), 
new.cat.lab = c(1, 1, 0, 0, 1, 1, 0, 1, 0, 1)), row.names = c(NA, 10L), class = "data.frame")

我想过滤 dt$new.cat.lab == 1 使用的行(来自 dplyr 包):

dt.match <- dt %>% filter(dt$new.cat.lab ==1, .preserve = T)

问题是过滤器函数分配了一个新的行号。我想在新变量中保留行号(索引)。 dplyr 的过滤功能中的.preserve=T 命令似乎没有这样做。

【问题讨论】:

    标签: r indexing filter dplyr row-number


    【解决方案1】:

    tidyverse,不保留行名,我们可以创建一个新的行名列,然后应用filter

    library(dplyr)
    library(tibble)
    dt %>%
       rownames_to_column('rn') %>%
       filter(new.cat.lab ==1)%>%
       column_to_rownames('rn')
    #   old.cat.lab new.cat.lab
    #1            1           1
    #2            1           1
    #5            0           1
    #6            1           1
    #8            0           1
    #10           1           1
    

    根据?dplyr::filter.preserve用于分组结构

    .preserve - .data 输入分组时相关。如果 .preserve = FALSE(默认),则根据结果数据重新计算分组结构,否则保持分组不变。


    base R 中,这可以通过subset 完成

    subset(dt, new.cat.lab == 1)
    

    或使用as.logical

    subset(dt, as.logical(new.cat.lab))
    

    【讨论】:

      【解决方案2】:
      library(dplyr)
      
      iris %>% 
        mutate(index = rownames(.)) %>% 
        relocate(index, .before = "Sepal.Length") %>% 
        subset(., Sepal.Length == max(Sepal.Length))
      

      使用行名/行号创建索引列以进行跟踪。然后过滤。下面是另一个变种

      iris %>% 
        mutate(index = rownames(.)) %>% 
        relocate(index, .before = "Sepal.Length") %>% 
        filter(Sepal.Length == max(Sepal.Length))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-04
        • 1970-01-01
        • 2023-03-08
        • 2021-03-07
        • 1970-01-01
        • 1970-01-01
        • 2023-02-10
        • 2023-02-10
        相关资源
        最近更新 更多