简体   繁体   English

当(A)是R中data.frame的特定条件时,如何使函数获得平均值(B)

[英]How to make a function to get average (B) when (A) is a certain condition on data.frame in R

this is for setting 这是为了设置

#this is for setting

A <- c(1,1,2,2,2,3,4,4,5,5,5)
B <- c(1:10)
C <- c(11:20)

ABC <- data.frame(A,B,C)

#so, I made up my own ABC like this    

   A  B  C
1  1  1 11
2  1  2 12
3  2  3 13
4  2  4 14
5  2  5 15
6  3  6 16
7  4  7 17
8  4  8 18
9  5  9 19
10 5 10 20

On this setting, I want to know, when (A) are in a specific condition, how to get average (B)or(C) 在此设置下,我想知道,当(A)处于特定条件下时,如何求平均值(B)或(C)

For example if condition(A) are 2:4, get mean (B), and mean(C) 例如,如果条件(A)为2:4,则获取均值(B)和均值(C)

new_ABC <- subset(ABC, ABC$A >= 2 & ABC$A <= 4)
mean(newABC$B)
mean(newABC$C)

and it works. 而且有效。

But if I want to make a function like this, I tried severe days, I have no idea... 但是如果我想做一个这样的功能,我尝试了很多天,我不知道...

getMeanB <- function(condition){
    for(i in min(condition) : max(condition){
        # I do not really know what to do..
    }
}

Any helps will very thanks!! 任何帮助将非常感谢!

If the argument 'condition' is a vector , then we can do it 如果参数“ condition”是一个vector ,那么我们可以做到

getMean <- function(data, condition, cName) {
    minC <- min(condition)
    maxC <- max(condition)
    i1 <- data[[cName]] >= minC & data[[cName]] <= maxC
   colMeans(data[i1,setdiff(names(data), cName)], na.rm = TRUE)
}

getMean(ABC, 2:4, "A")
#   B    C 
#  5.5 15.5 

NOTE: Here, the 'data' and 'cName' arguments are added to make it more dynamic and applied to other datasets with different column names. 注意:在此处,添加了“数据”和“ cName”参数以使其更加动态,并应用于具有不同列名的其他数据集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM