且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用R根据数据框中单个列的最小值对特定列中的行进行子集

更新时间:2023-08-28 16:23:40

我们可以使用 map 遍历按"ID"分组的"X0","V2"列,对行进行切片其中该循环列的值为 min ,将它们绑定在一起( _dfr )并使用这些列的 pmin 创建'd'列

We can use map to loop over the columns 'X0', 'V2', grouped by 'ID', slice the rows where the value is min for that looped column, bind them together (_dfr) and create the 'd' column with pmin of those columns

library(dplyr)
library(purrr)
nm1 <- names(df1)[5:6]
map_dfr(nm1, ~ df1 %>%
         group_by(ID) %>%
         slice_min(!! rlang::sym(.x))) %>% 
     ungroup %>%
     mutate(d = select(., all_of(nm1)) %>% reduce(pmin))

-输出

# A tibble: 4 x 7
#      X     Y ID       TI    X0    V2     d
#  <dbl> <dbl> <chr> <dbl> <dbl> <dbl> <dbl>
#1  8.47  48.0 B_1    191. 0.134 0.348 0.134
#2  7.59  48.7 B_1_2 1350. 0.361 0.771 0.361
#3  8.15  48.4 B_1    191. 0.846 0.141 0.141
#4  8.06  48.2 B_1_2 1350. 0.983 0.224 0.224