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

如何在R语言中统计列中大于指定值的行数并生成表格与折线图

解决方法

1. 构造示例数据

先把你提供的示例数据转换成R可识别的数据框:

# 构造数据框
data <- data.frame(
  height = c(192, 185, 174, 173, 172, 171, 170, 167, 167, 163),
  weight = c(74, 51, 50, 83, 74, 66, 51, 86, 66, 50),
  row.names = c("2th", "8th", "4th", "3th", "5th", "7th", "10th", "1th", "6th", "9th")
)

2. 统计大于指定值的行数

先定义你要统计的目标值(比如51、74),再批量计算每个值对应的行数:

# 指定要统计的目标值
target_values <- c(51, 74)

# 计算每个目标值对应的大于该值的行数
counts <- sapply(target_values, function(x) sum(data$weight > x))

# 生成结果表格
result_table <- data.frame(
  目标值 = target_values,
  大于该值的行数 = counts
)

# 查看表格
print(result_table)

运行后会得到如下结果:

目标值 大于该值的行数
1     51             6
2     74             2

3. 绘制线性折线图

方法一:基础R绘图

用R原生绘图工具快速生成折线图:

# 绘制带点标记的折线图
plot(target_values, counts, type = "b", 
     xlab = "目标体重值", ylab = "大于该值的行数",
     main = "体重阈值对应行数统计折线图",
     pch = 16, col = "blue", lwd = 2)

方法二:ggplot2绘图(更美观)

如果追求更精致的可视化效果,用ggplot2包实现:

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

ggplot(result_table, aes(x = 目标值, y = 大于该值的行数)) +
  geom_line(color = "blue", linewidth = 1) +
  geom_point(size = 3, color = "red") +
  labs(x = "目标体重值", y = "大于该值的行数", title = "体重阈值对应行数统计折线图") +
  theme_minimal()

补充:批量统计所有唯一体重值

如果需要统计weight列所有唯一值对应的大于该值的行数,可直接提取唯一值批量计算:

# 获取weight列的所有唯一值并排序
all_unique_weights <- sort(unique(data$weight))

# 统计每个唯一值对应的行数
all_counts <- sapply(all_unique_weights, function(x) sum(data$weight > x))

# 生成完整统计表格
full_result <- data.frame(
  体重值 = all_unique_weights,
  大于该值的行数 = all_counts
)

print(full_result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 09:30:09