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

如何筛选行:保留拥有至少3个唯一年份的州的全部数据

筛选拥有至少3个唯一年份的州数据

原始数据集

library(tibble)
data <- tibble(year=c(2010,2010,2012,2010,2011,2011,2013,2013,2010,2011,2012,2013),
               state=c("ca", "ca", "ca", "ny", "ny", "ny", "ny", "ny", "wa", "wa", "wa", "wa"), 
               variable2=c("a", "b", "c", "b", "c", "a", "d", "a", "b", "b", "c", "b"),
               value=c(6,5,2,6,3,1,7,8,3,2,5,7))

解决方案

使用dplyr包按州分组,筛选出唯一年份数量≥3的州,保留其全部数据:

library(dplyr)

# 筛选符合条件的州数据
filtered_data <- data %>%
  group_by(state) %>%
  filter(n_distinct(year) >= 3) %>%
  ungroup()

# 查看结果
print(filtered_data)

输出结果

# A tibble: 9 × 4
   year state variable2 value
  <dbl> <chr> <chr>     <dbl>
1  2010 ny    b             6
2  2011 ny    c             3
3  2011 ny    a             1
4  2013 ny    d             7
5  2013 ny    a             8
6  2010 wa    b             3
7  2011 wa    b             2
8  2012 wa    c             5
9  2013 wa    b             7

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 00:45:33