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

如何在R中按城市统计指定列的0、1数量及频率百分比?

按城市统计指定列中0和1的总数及频率百分比

方法1:使用tidyverse(推荐,代码直观易读)

先确保安装并加载tidyverse包:

install.packages("tidyverse") # 首次使用需安装
library(tidyverse)

假设你的数据框名为df,执行以下代码即可得到结果:

result <- df %>%
  # 将p54_1至p54_14列转换为长格式,统一处理所有目标列
  pivot_longer(cols = starts_with("p54_"), names_to = "col_name", values_to = "value") %>%
  # 筛选出值为0或1的记录
  filter(value %in% c(0, 1)) %>%
  # 按城市分组统计
  group_by(City) %>%
  summarise(
    count_01 = n(), # 0和1的总数
    total_entries = nrow(df[df$City == cur_group()$City, ]) * 14, # 该城市所有目标列的总条目数
    freq_percent = round((count_01 / total_entries) * 100, 2) # 频率百分比,保留两位小数
  ) %>%
  ungroup()

# 查看结果
print(result)

代码说明:

  • pivot_longer:把分散在14列的数值整合到一列中,避免重复写多列逻辑
  • filter:精准筛选出需要统计的0和1
  • group_by + summarise:按城市分组后,一次性计算总数、总条目数和频率百分比

方法2:使用Base R(无需额外安装包)

如果不想加载第三方包,可以用原生R代码实现:

# 定位所有p54开头的列
target_cols <- grep("^p54_", names(df))

# 按城市统计0和1的总数
count_01 <- tapply(
  unlist(df[, target_cols]),
  rep(df$City, length(target_cols)),
  function(x) sum(x %in% c(0, 1))
)

# 计算每个城市的总条目数
total_entries <- tapply(
  unlist(df[, target_cols]),
  rep(df$City, length(target_cols)),
  length
)

# 计算频率百分比并整理成数据框
result_base <- data.frame(
  City = names(count_01),
  count_01 = as.numeric(count_01),
  total_entries = as.numeric(total_entries),
  freq_percent = round((count_01 / total_entries) * 100, 2),
  row.names = NULL
)

# 查看结果
print(result_base)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 14:09:59