如何按行过滤数据帧而不丢失索引(或行号)?

问题描述 投票:0回答:1

我有一个小的数据框(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")

我想使用(从dplyr包中)过滤dt$new.cat.lab == 1所在的行:

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

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

r indexing filter dplyr row-number
1个回答
0
投票

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

base R中,可以用subset来完成>

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

或使用as.logical

subset(dt, as.logical(new.cat.lab))
© www.soinside.com 2019 - 2024. All rights reserved.