[英]Average and count with aggregation in R with dplyr
我想計算變量價格等於0,49的元素數量,或者如果還有其他我想要的數量,但我不在乎這個價格多少錢。 如果這個不等於0或49,我想通過終端做平均價格
terminal <- c("a", "b", "a", "c", "b", "b")
price <- c(0, 49, 3.5, 0, 17, 32)
df <- data.frame(terminal, price)
df %>%
group_by(terminal, price) %>%
summarise(count = n())
在這里我想要計算:1,1,2,1,1,之后我想得到終端價格的平均值,當這個不等於零或49時。
我們需要根據值“0”和“49”創建一個具有“價格”的分組變量。 為此,一種方法是使用==
來獲得0和49的邏輯索引,做一些算術,以便我們將有3個組一個用於0,一個用於49,其余用於所有其他組。 通過'terminal'和'gr'分組,我們summarise
得到行數,即'n'和'price'的mean
不是0或49(使用%in%
和否定!
)
library(dplyr)
df %>%
group_by(terminal, gr= 1+2*(price==0)+4*(price==49)) %>%
summarise(n=n(),
Avg = mean(price[!(price %in% c(0,49))], na.rm=TRUE))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.