我有一个大约45k点的数据框,有3列 - 重量,人数和人口。人口是重量*人。我希望能够根据需要将数据框分成ntiles(十分位数,百分位数等)。必须以每个ntile中具有相同数量的人口点的方式拆分数据框 这意味着,数据框需要以value = sum(population)/ ntile进行拆分。因此,例如,如果ntile = 10,则sum(population)/ 10 = a。接下来我需要在population列中添加行值,直到sum = a,在该点分割并继续,直到我遍历所有45K点。下面是一个数据样本。
weight persons population
1 3687.926 9 33191.337
2 3687.926 16 59006.8217
3 3687.926 7 25815.4847
4 4420.088 5 22100.447
5 4420.088 7 30940.6167
6 4420.088 6 26520.5287
7 3687.926 15 55318.8927
8 3687.926 9 33191.3357
9 3687.926 6 22127.5577
10 4452.829 8 35622.6367
11 4452.829 3 13358.4887
12 4452.829 4 17811.3187
我一直在尝试使用循环。我坚持将数据帧拆分为所需的n个拆分。我是R.的新人。所以任何帮助都表示赞赏。
x= df$population
break_point = sum(x)/10
ntile_points = 0
for(i in 1:length(x))
{
while(ntile_points != break_point)
{
ntile_points = ntile_points+x[i]
}
}
x= df$population
break_point = sum(x)/10
ntile_points = 0
for(i in 1:length(x))
{
while(ntile_points != break_point)
{
ntile_points = ntile_points+x[i]
}
}
答案 0 :(得分:0)
我不确定这是你想要的,请注意你的分位数不是一个整数,你应该在每个断点之间减去:
ntile=10
df=cbind(df,cumsum(df$population))
names(df)[ncol(df)]='Cumsum'
s=seq(0,sum(df$population),sum(df$population)/ntile)
subdfs=list()
for (i in 2:length(s)){
subdfs=c(subdfs,list(df[intersect(which(df$Cumsum<=s[i]),which(df$Cumsum>s[i-1])),]))
}
然后subdfs
是一个包含10个数据帧的列表,如您所愿。使用subdfs[[1]]
调用第一个数据框,依此类推。也许我不明白你想要什么,告诉我。
通过这种方式,第一个df包含所有第一个值,直到总体的累积总和保持在interval] 0,sum(population)/ 10],第二个包含,以下值,其中人口的累积总和在区间]总和(人口)/ 10,2 *总和(人口)/ 10]等....
这就是你想要的吗?