【问题标题】:How to calculate mean for variables based on value of another variable?如何根据另一个变量的值计算变量的平均值?
【发布时间】:2021-06-14 06:18:16
【问题描述】:

R 新手,这是我目前正在使用的数据集。

    i Y X
1   1 3 1
2   2 2 1
3   3 1 1
4   4 1 1
5   5 4 1
6   6 5 2
7   7 2 2
8   8 4 2
9   9 2 2
10 10 3 2
11 11 7 3
12 12 4 3
13 13 5 3
14 14 3 3
15 15 6 3

我如何计算 X 值 >1 的变量的 Y 平均值。 (本例中的第 6-15 行)

【问题讨论】:

    标签: r dataframe mean


    【解决方案1】:

    我们可以使用“X”中的逻辑表达式来子集“Y”值并得到mean

    with(df, mean(Y[X > 1]))
    #[1] 4.1
    

    或使用collapse 中的fsubsetfmean 更有效地完成此操作

    library(collapse)
    fmean(fsubset(df, X > 1)$Y)
    #[1] 4.1
    

    数据

    df <- structure(list(i = 1:15, Y = c(3L, 2L, 1L, 1L, 4L, 5L, 2L, 4L, 
    2L, 3L, 7L, 4L, 5L, 3L, 6L), X = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 
    2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L)), class = "data.frame", row.names = c("1", 
    "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", 
    "14", "15"))
    

    【讨论】:

      最近更新 更多