我有一个小的数据框(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
命令似乎没有执行该操作。
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))