找到范围并平均R中的相应元素

时间:2014-10-24 09:39:39

标签: r range average

我在一个数据集中有不同的数字范围(或坐标),我想找到合适的数字范围,然后取相应分数的平均值。

让我说我的数据集是:

coordinate score    
     1000   1.1
     1001   1.2
     1002   1.1
     1003   1.4
     1006   1.8
     1007   1.9
     1010   0.5
     1011   1.1
     1012   1.0

我应该找到合适的边界(当coordinate不连续时),然后计算每个特定范围的平均值。

我想要的结果:

start end mean-score
1000 1003  1.2
1006 1007  1.85
1010 1012  0.86

1 个答案:

答案 0 :(得分:3)

试试这个(假设df是您的数据集)

library(data.table)
setDT(df)[, indx := .GRP, by = list(cumsum(c(1, diff(coordinate)) - 1))]
df[, list(start = coordinate[1],
          end = coordinate[.N],
          mean_score = round(mean(score), 2)), by = indx]

#    indx start  end mean_score
# 1:    1  1000 1003       1.20
# 2:    2  1006 1007       1.85
# 3:    3  1010 1012       0.87

或使用dplyr

library(dplyr)
df %>%
  mutate(indx = dense_rank(cumsum(c(1, diff(coordinate)) - 1))) %>%
  group_by(indx) %>%
  summarise(start = first(coordinate),
            end = last(coordinate),
            mean_score = round(mean(score), 2))

# Source: local data frame [3 x 4]
# 
#   indx start  end mean_score
# 1    1  1000 1003       1.20
# 2    2  1006 1007       1.85
# 3    3  1010 1012       0.87

以下是一些替代性基础R解决方案(效率低得多)

df$indx <- as.numeric(factor(cumsum(c(1, diff(df$coordinate)) - 1)))
cbind(aggregate(coordinate ~ indx, df, function(x) c(start = head(x, 1), end = tail(x, 1))),
      aggregate(score ~ indx, df, function(x) mean_score = round(mean(x), 2)))

#   indx coordinate.start coordinate.end indx score
# 1    1             1000           1003    1  1.20
# 2    2             1006           1007    2  1.85
# 3    3             1010           1012    3  0.87

或者

cbind(do.call(rbind, (with(df, tapply(coordinate, indx, function(x) c(start = head(x, 1), end = tail(x, 1)))))),
with(df, tapply(score, indx, function(x) mean_score = round(mean(x), 2))))

#   start  end     
# 1  1000 1003 1.20
# 2  1006 1007 1.85
# 3  1010 1012 0.87