[英]R: Count rows in dataframe based on criteria from a different dataframe
所以我有兩個數據框-
個人數據
person_id | date | present_absent
1 12/9 p
2 12/9 a
3 12/9 p
1 20/9 a
2 20/9 a
3 20/9 a
...
每日數據
date | week_code | absence_count
12/9 A
20/9 B
...
我需要計算出daily.data框架中的每個日期,在person.data框架中記錄了多少個“ a”代碼,並將結果記錄在daily.data框架的missing_count列中。
問題的一部分是我不知道如何在不舉例子的情況下正確地表達問題。 我最近的4個小時的google和stackoverflow搜索顯示了如何使用以下方法計算特定日期的'a'代碼數量:
sum(person.data$date == 12/9 & person.data$present_absent == "a")
但我不知道如何將其與person.data $ date和每個daily.data $ date進行比較。 我可以使用Excel並使用COUNTIFS()公式,但是我真的很想了解R。
在此先感謝您的幫助。
您可以在R中使用合計和%in%函數。
# Your first dataset
person.data <- data.frame("persion_id" = c(1,2,3,1,2,3),
"date" = c("12/9", "12/9", "12/9","20/9", "20/9", "20/9"),
"present_absent" = c("p", "a", "p", "a", "a", "a"))
# Your second dataset you want to populate
daily.data <- data.frame("date" = c("12/9", "20/9"),
"week_code" = c("A", "B"))
# Summarize the attendance for all dates
summary <- aggregate(as.integer(person.data$present_absent),
by = list(person.data$date, person.data$present_absent), FUN = sum)
# Get only the absent records from summary
daily.data$absence_count <- summary[(daily.data$date %in% person.data$date &
summary[,2] == "a"), 3]
dplyr
解決方案:
library(dplyr)
inner_join(person.data, daily.data) %>%
group_by(date, week_code) %>%
summarize(absence_count = sum(present_absent == 'a'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.