使用聚合函数查找每个组中不为零的最小值

时间:2019-06-19 11:00:34

标签: r

我有以下数据集:

6b9691fa    1   0   2   1   4
6b9691fa    1   1   -1  1   5
6b9691fa    1   2   3   0   4
6b9691fa    2   0   1   5   3
6b9691fa    2   1   0   5   3
6b9691fa    2   2   3   5   3
6b9691fa    3   0   10  1   9
6b9691fa    3   1   10  0   9
6b9691fa    3   2   10  1   9

我想在第二列的每组(即三组分别是1、2和3)的第四,第五和第六列中找到最小值。最小值不应为零。为此,我执行了以下操作:

 aggregate(dataset[,4:6], list(dataset$V2), min)

但是返回零。为了避免最小为零,我该怎么办?

3 个答案:

答案 0 :(得分:8)

这可能就是您想要的:

dataset <- read.table(text = '6b9691fa    1   0   2   1   4
6b9691fa    1   1   -1  1   5
6b9691fa    1   2   3   0   4
6b9691fa    2   0   1   5   3
6b9691fa    2   1   0   5   3
6b9691fa    2   2   3   5   3
6b9691fa    3   0   10  1   9
6b9691fa    3   1   10  0   9
6b9691fa    3   2   10  1   9')

aggregate(x = dataset[, 4:6],
          by = list(dataset[, 2]),
          FUN = function(t) min(t[t != 0]))
#>   Group.1 V4 V5 V6
#> 1       1 -1  1  4
#> 2       2  1  5  3
#> 3       3 10  1  9

reprex package(v0.3.0)于2019-06-19创建

答案 1 :(得分:4)

使用data.table

setDT(dataset)
dataset[, lapply(.SD, function(x) min(x[x != 0])), by = V2, .SDcols = V4:V6]
#    V2 V4 V5 V6
# 1:  1 -1  1  4
# 2:  2  1  5  3
# 3:  3 10  1  9

答案 2 :(得分:2)

只需使用summarise_each中的dplyr

df <- fread("Col1 Col2 Col3 Col4 Col5 Col6
6b9691fa    1   0   2   1   4
6b9691fa    1   1   -1  1   5
6b9691fa    1   2   3   0   4
6b9691fa    2   0   1   5   3
6b9691fa    2   1   0   5   3
6b9691fa    2   2   3   5   3
6b9691fa    3   0   10  1   9
6b9691fa    3   1   10  0   9
6b9691fa    3   2   10  1   9")

df %>% group_by(Col2) %>%
  summarise_each(function(x) min(x[x != 0]),Col4:Col6)


# A tibble: 3 x 4
   Col2  Col4  Col5  Col6
  <int> <int> <int> <int>
1     1    -1     1     4
2     2     1     5     3
3     3    10     1     9
相关问题