我如何在R中建立一个循环函数来计算每个年龄单位(1-2,2-3,3-4和,,,18-19)在粉红线之外的点数(百分比)?我的意思是,例如,我想知道在1-2岁之间的年龄间隔中有多少个点的值比那个特定年龄间隔的估计粉红色曲线要高,然后计算出百分比(值高于估计值的点数除以该特定区间的观察总数)?我需要为每一个单位年龄间隔(1-2,2-3,3-4,4-5,5-6,6-7,,,17-18,18-19)。
例如:
Age Value estimated Value
1.5 12 12
1.5 12 14
1.7 13 15
1.8 14 9
2.1 12 15
2.2 14 16
2.3 14 13
3 8 8.1
4 9 9.1
4.1 5 6.1
4.2 5 12
5 14 15
The result should be something like
Age: 1-2 2-3 3-4 4-5
number of points *outside* 1 1
percentage 1/4 1/3 我的初始代码:(但我需要把它作为循环函数来获得所有年龄单位的结果)
a=1
b=2
A<-subset(Data, Age>=a & Age<b)
sum(A$Value > A$EstimatedValue)/nrow(A)

发布于 2018-11-15 15:45:26
使用dplyr
library(dplyr)
dd %>%
mutate(age_bin = cut(Age, breaks = 0:20)) %>%
group_by(age_bin) %>%
summarize(n_points = n(),
n_over_estimate = sum(Value > estimated_Value),
pct_over_estimate = n_over_estimate / n_points * 100)
# age_bin n_points n_over_estimate pct_over_estimate
# <fct> <int> <int> <dbl>
# 1 (1,2] 4 1 25
# 2 (2,3] 4 1 25
# 3 (3,4] 1 0 0
# 4 (4,5] 3 0 0这些样本数据如下:
dd = read.table(text = "Age Value estimated_Value
1.5 12 12
1.5 12 14
1.7 13 15
1.8 14 9
2.1 12 15
2.2 14 16
2.3 14 13
3 8 8.1
4 9 9.1
4.1 5 6.1
4.2 5 12
5 14 15", header = TRUE)https://stackoverflow.com/questions/53322037
复制相似问题