在带有负数和正数的数据框中查找最大负数和最小正数

I would like to take the maximum negative value of a column containing negatives and positives (diff_start), and minimum positive value of another column (diff_end) in R.

数据:

data <- read.table(text ="
                   id lab diff_start diff_end
                   1 hb -1.7 -1.8
                   1 hb -0.3 -0.3
                   1 hb 0.6 0.5
                   1 hb 0.7 0.8", header = TRUE)

所需输出:

# id lab   diff_start diff_end
# 1 hb     -0.3      0.5

我做了什么:

  • Split the data into 2, and filter <= 0 for diff_start and >= 0 for diff_end
  • Obtain the summaries of interest, and then merge them back

我认为这很长且效率很低,希望使其更加简洁。

full_join(
  data %>% 
    group_by(id, lab) %>% 
    filter(diff_start <= 0) %>% 
    summarise(diff_start = max(diff_start)) %>% 
    ungroup(),
  data %>% 
    group_by(id, lab) %>% 
    filter(diff_start >= 0) %>% 
    summarise(diff_end = min(diff_end)) %>% 
    ungroup())