r - dplyr 变异 : Excluding observations similar to the current one

标签 r mean dplyr

我有一些这样的数据:

X   Y
-----
A   1
A   2
B   3
B   4
C   5
C   6

我想添加一个新列,其值等于行中所有 Y 的平均值,其中 X 不等于当前观察的 X。 在这种特殊情况下,我们会得到

X   Y   Mean
-------------------
A   1   (3+4+5+6)/4
A   2   (3+4+5+6)/4
B   3   (1+2+5+6)/4
B   4   (1+2+5+6)/4
C   5   (1+2+3+4)/4
C   6   (1+2+3+4)/4

提前致谢!

最佳答案

您可能会更简洁地执行此操作,但这会给您带来结果。

您实际上创建了一个列,其中包含整个 data.frame 的总观察值和记录总和。然后按 X 列分组并重复该过程,通过取差可以计算平均值。

数据

df <- data.frame(X = c("A", "A", "B", "B", "C", "C"),
                 Y = c(1:6))

解决方案

library(tidyverse)
df %>%
  mutate(total_sum = sum(Y),
         total_obs = n()) %>%
  group_by(X) %>%
  mutate(group_sum = sum(Y),
         group_obs = n()) %>%
  ungroup() %>%
  mutate(other_group_sum = total_sum - group_sum,
         other_group_obs = total_obs - group_obs,
         other_mean = other_group_sum/other_group_obs) %>%
  select(X, Y, other_mean)

结果

# A tibble: 6 x 3
  X         Y other_mean
  <fct> <int>      <dbl>
1 A         1       4.50
2 A         2       4.50
3 B         3       3.50
4 B         4       3.50
5 C         5       2.50
6 C         6       2.50

关于r - dplyr 变异 : Excluding observations similar to the current one,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49355183/

相关文章:

r - 使用 rlang 包解析引用参数

r - ggplot2 盒须图 : show 95% confidence intervals & remove outliers

r - 如何在这个由几个不同的几何图形组成的ggplot中手动指定图例文本/颜色?

c++ - 带行的列 vector - 带 std::accumulate?

r - dplyr:以字符串作为列名的条件过滤器

r - 在 R 中使用 mutate 重命名列中的项目

r - pamk 函数中的参数

r - 使用 R,获取 "Can' t 绑定(bind)数据,因为某些参数具有相同的名称”使用 dplyr :select

python - Pandas:计算平均值,忽略自己行的值

javascript - 脚本不会在浏览器中加载 angular2