简体   繁体   中英

R Studio: Average multiple columns with conditional logic

In R studio, how can I get one average of multiple columns with conditional logic for one of the columns? For example, I have a dataset, called 'test' of the below 5 columns. I want to get one combined average for columns A, B, and C. But I only want to include Column C in the average if Flag is equal to 1 for a cell in Column C.

    ID<-c(1,2,3)
    A<-c(1,0,NA)
    B<-c(0,NA,1)
    C<-c(1,1,1)
    Flag<-c(0,1,1)
   test<-as.data.frame(cbind(ID,A,B,C,Flag))

[click here to see my data set]

So I want: Average = (All cells in column A + All cells in column B + Only cells in column C where cells in Flag column is equal to 1 )

We unlist the dataset with a subset of columns ("A", "B"), concatenate with the values of "C" that corresponds to "Flag" of 1 and get the mean .

mean(c(unlist(test[c("A", "B")]), test$C[test$Flag==1]), na.rm=TRUE)
#[1] 0.6666667

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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