【发布时间】:2017-10-20 17:45:36
【问题描述】:
我的数据框 (hh_dist_points) 具有以下结构:
hh_dist_points <- read.table(header=TRUE ,text="
hhid VillageID hhid_1 VillageI_1 NEAR_DIST
2739 405050508 2730 405050508 8.300739e+01
2739 405050508 2588 405050508 9.717326e+01
2739 405050508 2825 405050508 1.335821e+02
2739 405050508 2823 405050508 1.631118e+02
2739 405050508 2729 405050508 1.964680e+02
2739 405050508 2810 405050508 2.243312e+02
2739 405050508 2828 405050508 2.889768e+02
2739 405050508 2725 405050502 8.808605e+02
2739 405050508 2822 405050502 9.084585e+02
2739 405050508 2731 405050502 9.222313e+02
2739 405050508 2742 405050502 9.681594e+02
2739 405050508 2741 405050502 1.026474e+03")
原始数据集包含约。 2000 个观察值(1 个观察值 = 一个村庄中的房屋 (hhid)。属于同一村庄的房屋具有相同的 VillageID(约 10 个具有相同 ID 的观察值)。 Near_Dist:2 个房屋之间的测地距离(hhid) 上面的数据框显示了我的数据集 (hhid_1) 中每个房子 (hhid) 到所有其他房子的距离(总共超过 3 个 Mio. 行)。
我的目标: 根据相同的 VillageID 计算每组观测值 (hhid) 的 Near_Dist 的平均值,并将结果存储在新的数据框中:
VillageID dist_mean
405050508 963,257416
405050502 823,21464
..... .........
总体思路:如果 VillageID = VillageID_1,则计算 Near_Dist 的平均值并将结果存储在新的数据框中。
我的想法是使用循环:
if(hh_dist_points$VillageID = hh_dist_points$VillageI_1) {
hh_dist_new <- mean(hh_dist$NEAR_DIST)
}
else
但我知道这是不正确的(并且未完成),但我不知道如何完成它。 任何想法如何简单地解决这个问题? (也许不使用循环)。 我试图搜索任何答案和解决方案,但我没有找到任何答案。
我需要数据框进行其他计算。 非常感谢四你的帮助。
【问题讨论】:
-
你的 'hh_dist_points$VillageID = hh_dist_points$VillageI_1' 需要是 '==' :)
标签: r loops if-statement dataframe mean