根据多个条件删除组上的行r

根据多个条件删除组上的行r,r,dplyr,R,Dplyr,我有一个数据集,在日期变量上有一些重复的值,所以我想根据几个条件筛选这些行。例如,dataframe如下所示: df <- read.table(text = "Date column_A column_B column_C Column_D 1 2020-01-01 10 15 15 20 2 2020-01-02 10

我有一个数据集,在日期变量上有一些重复的值,所以我想根据几个条件筛选这些行。例如,dataframe如下所示:

df <- read.table(text = 
          "Date       column_A   column_B    column_C   Column_D
1        2020-01-01     10          15         15          20
2        2020-01-02     10          15         15          20
3        2020-01-03     10          13         15          20
4        2020-01-04     10          15         15          20
5        2020-01-05     NA          14         15          20
6        2020-01-05     7           NA         NA          28
7        2020-01-06     10          15         15          20
8        2020-01-07     10          15         15          20
9        2020-01-07     10          NA         NA          20
10       2020-01-08     10          15         15          20", header=TRUE)

df$Date <- as.Date(df$Date)

df我会根据您的条件对您的表格进行排序,然后为每组选择第一行:

library(dplyr)

df %>% 
  rowwise() %>% 
  mutate(cnt_na = sum(across(-Date, ~ sum(is.na(.))))) %>% 
  arrange(Date, is.na(column_A), cnt_na) %>% 
  group_by(Date) %>% 
  slice_head() %>% 
  ungroup()

# A tibble: 8 x 6
  Date       column_A column_B column_C Column_D cnt_na
  <date>        <int>    <int>    <int>    <int>  <int>
1 2020-01-01       10       15       15       20      0
2 2020-01-02       10       15       15       20      0
3 2020-01-03       10       13       15       20      0
4 2020-01-04       10       15       15       20      0
5 2020-01-05        7       NA       NA       28      2
6 2020-01-06       10       15       15       20      0
7 2020-01-07       10       15       15       20      0
8 2020-01-08       10       15       15       20      0
#一个tible:8 x 6
日期列A列B列C列D列cnt
1 2020-01-01       10       15       15       20      0
2 2020-01-02       10       15       15       20      0
3 2020-01-03       10       13       15       20      0
4 2020-01-04       10       15       15       20      0
5 2020-01-05 7 NA 28 2
6 2020-01-06       10       15       15       20      0
7 2020-01-07       10       15       15       20      0
8 2020-01-08       10       15       15       20      0
# A tibble: 8 x 6
  Date       column_A column_B column_C Column_D cnt_na
  <date>        <int>    <int>    <int>    <int>  <int>
1 2020-01-01       10       15       15       20      0
2 2020-01-02       10       15       15       20      0
3 2020-01-03       10       13       15       20      0
4 2020-01-04       10       15       15       20      0
5 2020-01-05        7       NA       NA       28      2
6 2020-01-06       10       15       15       20      0
7 2020-01-07       10       15       15       20      0
8 2020-01-08       10       15       15       20      0