[英]R: Count Number of Observations within a group
使用 R 編程語言,我正在嘗試在此處遵循本教程: 在 R 中計算每天、每月和每年的觀察次數
我每天創建數據,然后每周對這些數據進行匯總。 在“y.week”文件中,我想添加一個“計數”列,列出每周的觀察次數。
這是我正在使用的以下代碼:
#load libraries
library(xts)
library(ggplot2)
#create data
date_decision_made = seq(as.Date("2014/1/1"), as.Date("2016/1/1"),by="day")
date_decision_made <- format(as.Date(date_decision_made), "%Y/%m/%d")
property_damages_in_dollars <- rnorm(731,100,10)
final_data <- data.frame(date_decision_made, property_damages_in_dollars)
#aggregate and count by week
y.week <-aggregate(property_damages_in_dollars~format(as.Date(date_decision_made),
format="%W-%y"),data=final_data, FUN=sum)
counts_week <- data.frame(table(as.Date(index(y.week))))
y.week$count = count_week
但我不認為這是正確的。
然后我嘗試每月做同樣的事情:
#aggregate and count by month
y.mon<-aggregate(property_damages_in_dollars~format(as.Date(date_decision_made),
format="%Y/%m"),data=final_data, FUN=sum)
counts_mon <- data.frame(table(as.Date(index(y.mon))))
y.mon$count = count_mon
通常,我會使用“dplyr”庫按組計數(按月計數,按周計數),但我不確定如何“告訴”dplyr 在同一周(或同一個月)考慮觀察結果作為一個團隊”。
有人可以告訴我我做錯了什么嗎?
謝謝
編輯:可能的答案(由 Ronak Shah 提供):
按周:
date_decision_made = seq(as.Date("2014/1/1"), as.Date("2016/1/1"),by="day")
date_decision_made <- format(as.Date(date_decision_made), "%Y/%m/%d")
property_damages_in_dollars <- rnorm(731,100,10)
final_data <- data.frame(date_decision_made, property_damages_in_dollars)
final_data %>%
mutate(date_decision_made = as.Date(date_decision_made)) %>%
group_by(week = format(date_decision_made, "%W-%y")) %>%
summarise( total = sum(property_damages_in_dollars, na.rm = TRUE), Count = n())
按月份:
date_decision_made = seq(as.Date("2014/1/1"), as.Date("2016/1/1"),by="day")
date_decision_made <- format(as.Date(date_decision_made), "%Y/%m/%d")
property_damages_in_dollars <- rnorm(731,100,10)
final_data <- data.frame(date_decision_made, property_damages_in_dollars)
final_data %>%
mutate(date_decision_made = as.Date(date_decision_made)) %>%
group_by(week = format(date_decision_made, "%Y-%m")) %>%
summarise( total = sum(property_damages_in_dollars, na.rm = TRUE), Count = n())
如果您保持對象的自然形式會更好。 例如,將日期保留為日期而不是字符串。 然后你可以使用
library(dplyr)
final_data %>%
mutate(date_decision_made = as.Date(date_decision_made)) %>%
add_count(week = format(date_decision_made, "%W-%y"), name = 'Count')
使用add_count
是使用group_by
+ mutate
和n()
的快捷方式:
final_data %>%
mutate(date_decision_made = as.Date(date_decision_made)) %>%
group_by(week = format(date_decision_made, "%W-%y")) %>%
mutate(Count = n())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.