You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R中统计2000年指定日期状态为T的观测数量

问题:统计2000年指定日期中状态为T的观测数量

给定如下R数据集:

dates = c("12/27/1999", "02/14/2000",
  "01/07/2000", "01/09/2000", "02/04/2000", "09/04/2000", "01/08/2001",
  "10/01/1998", "04/05/2000", "02/09/2001")

status = c("T", "F", 
           "T", "F", "T", "F", "T",
           "F", "T", "F")


df <- data.frame(letter = c(rep("a", 2), 
                            rep("b", 5),
                            rep("c", 3)),
                 status_code = c(12,3,15,45,16,3,35,24,19,22),
                 date = as.Date(dates, "%m/%d/%y"),
                 status = status)

需要统计2000年某一指定日期中状态为T的观测数量,无需生成全年完整结果表,以下是几种实用解决方法:

方法1:基础R实现

  1. 先定义目标日期(格式需与df$date一致,即YYYY-MM-DD):
target_date <- as.Date("2000-02-04")
  1. 用sum()结合条件筛选计数:
count_T <- sum(df$date == target_date & df$status == "T" & format(df$date, "%Y") == "2000", na.rm = TRUE)
  • 说明:df$date == target_date匹配指定日期,df$status == "T"匹配目标状态,format(df$date, "%Y") == "2000"确保年份为2000(若目标日期已明确是2000年可省略),na.rm = TRUE处理可能的缺失值。

方法2:dplyr包实现(管道式操作更直观)

若习惯使用tidyverse工具链,可采用dplyr:

  1. 先安装并加载包:
install.packages("dplyr")
library(dplyr)
  1. 筛选并统计行数:
target_date <- as.Date("2000-02-04")

count_T <- df %>%
  filter(date == target_date, status == "T", format(date, "%Y") == "2000") %>%
  nrow()
  • 说明:filter()按条件筛选符合要求的行,nrow()直接统计筛选后的观测数;也可使用lubridate::year(date) == 2000提取年份(需先安装lubridate包)。

注意事项

  • 确保目标日期格式与df$date的Date类型一致,避免格式不匹配导致筛选失败;
  • 若数据存在缺失值,需通过na.rm = TRUE(基础R)或!is.na(date)(dplyr)排除缺失行的干扰。

内容的提问来源于stack exchange,提问作者Mathica

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 23:25:27