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

如何在R语言Data Frame中获取3居室房屋的索引/ID及价格?

在R语言Data Frame中查找特定值的索引并关联房源信息

核心方法:查找特定值的索引

在R中,有两种简单直接的方式获取Data Frame中符合条件的行索引:

  1. 使用which()函数精准定位索引:
# 获取bedrooms列值为3的所有行索引
three_bed_indices <- which(new_data$bedrooms == 3)
  1. 用布尔索引直接筛选整行数据(同时保留索引与其他列信息):
# 筛选所有3居室的房源数据,包含完整列信息
three_bed_homes <- new_data[new_data$bedrooms == 3, ]

解决你的需求:输出带索引/ID的3居室价格

你原代码存在逻辑问题:循环中仅当遇到3居室时才递增index,这会导致index与实际行号错位,无法正确对应房源。以下是修正后的代码,可同时输出房源的行索引(或自定义ID)和价格:

方案1:输出行索引+价格

new_data <- read.csv("LR.csv")
# 筛选3居室数据
three_bed_homes <- new_data[new_data$bedrooms == 3, ]
# 逐行输出房源索引与价格
for (row_num in seq(nrow(three_bed_homes))) {
  cat("房源行索引:", rownames(three_bed_homes)[row_num], ",价格:", three_bed_homes$price[row_num], "\n")
}
# 输出3居室总数
cat("3居室房屋总数:", nrow(three_bed_homes), "\n")

方案2:若数据包含自定义房源ID列(如property_id)

如果CSV文件中有专门的房源ID列,只需调整输出内容:

new_data <- read.csv("LR.csv")
three_bed_homes <- new_data[new_data$bedrooms == 3, ]
for (row_num in seq(nrow(three_bed_homes))) {
  cat("房源ID:", three_bed_homes$property_id[row_num], ",价格:", three_bed_homes$price[row_num], "\n")
}
cat("3居室房屋总数:", nrow(three_bed_homes), "\n")

简洁批量输出

若不需要逐行打印,可直接筛选目标列批量查看:

# 仅显示价格列(若有ID列则改为c("property_id", "price"))
print(three_bed_homes[, "price"])

内容的提问来源于stack exchange,提问作者Divya Ranjan Pradhan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 09:33:22