首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >R中一个计算估计曲线外点数的循环函数

R中一个计算估计曲线外点数的循环函数
EN

Stack Overflow用户
提问于 2018-11-15 14:49:03
回答 1查看 58关注 0票数 0

我如何在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)。

例如:

代码语言:javascript
复制
   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                 

我的初始代码:(但我需要把它作为循环函数来获得所有年龄单位的结果)

代码语言:javascript
复制
a=1
b=2
A<-subset(Data, Age>=a & Age<b)
sum(A$Value > A$EstimatedValue)/nrow(A)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-15 15:45:26

使用dplyr

代码语言:javascript
复制
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

这些样本数据如下:

代码语言:javascript
复制
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)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53322037

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档