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

在R中统计满足方向一致且Pred在Trend±5%范围内的Cty数量

Solution for Counting Matching Counties in data.table

Here's how you can calculate the number of counties (Cty) that meet both your criteria using data.table in R:

Step 1: Ensure you have the data.table package loaded

First, make sure you've installed and loaded the data.table package if you haven't already:

install.packages("data.table") # Only run once if not installed
library(data.table)

Step 2: Calculate the count

Use this one-liner to filter rows that meet both conditions and count them:

matching_count <- Table1[
  Trend != 0 &  # Avoid division by zero (since % of 0 doesn't make sense)
  Pred * Trend > 0 &  # Same sign (both positive or both negative)
  abs((Pred - Trend) / Trend) <= 0.05,  # Pred is within ±5% of Trend
  .N  # Count the number of rows that satisfy the conditions
]

Explanation of the conditions:

  • Same sign check: Pred * Trend > 0 ensures both values are either positive or negative (since positivepositive and negativenegative result in a positive number; zero values are excluded by the first condition).
  • ±5% range check: abs((Pred - Trend)/Trend) <= 0.05 calculates the relative difference between Pred and Trend, ensuring it's within 5%. This works correctly for both positive and negative values of Trend without needing separate logic for each case.
  • Division by zero guard: Trend != 0 prevents errors if any Trend values are zero (since you can't calculate a percentage of zero in this context).

Example with your sample data

Using the rows you provided:

  • Adams: Relative difference is way over 5%
  • Alexander: Opposite signs
  • Bond: Opposite signs
  • Boone: Relative difference is way over 5%

So matching_count would return 0 for your sample data.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:28:51