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

R语言按缺失观测数条件计算1991-2000年各国均值方法

实现方案

基础R写法

直接基于你已有的缺失值统计逻辑组合即可:

# 统计1991-2000年每国缺失值数量
na_cnt <- rowSums(is.na(countrydata[, 33:42]))
# 筛选缺失值≤2的国家,计算对应时段均值
res <- data.frame(
  country = countrydata$country[na_cnt <= 2],
  mean_aid_1991_2000 = rowMeans(countrydata[na_cnt <= 2, 33:42], na.rm = TRUE)
)

说明:na.rm = TRUE参数会在计算均值时自动忽略存在的少量缺失值,如果你需要存在缺失时返回NA,删除该参数即可。

更稳妥的tidyverse写法(无需匹配列序号)

如果担心数据集列顺序变动导致选列错误,用列名匹配的方式更安全:

library(dplyr)

res <- countrydata %>%
  # 计算指定时段缺失值数量
  mutate(na_cnt = rowSums(is.na(pick(aid1991:aid2000)))) %>%
  # 筛选符合要求的国家
  filter(na_cnt <= 2) %>%
  # 计算均值
  mutate(mean_aid_1991_2000 = rowMeans(pick(aid1991:aid2000), na.rm = TRUE)) %>%
  # 保留所需输出字段
  select(country, mean_aid_1991_2000)

内容的提问来源于stack exchange,提问作者B.Nin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:36:04