【问题标题】:A loop function in R to count the number of points outside the estimatedcurveR中的循环函数,用于计算估计曲线之外的点数
【发布时间】:2018-11-15 14:49:03
【问题描述】:

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

【问题讨论】:

  • 你要计算yi - f(xi)。如果f 是矢量化的,则不需要循环。如果您需要更多帮助,请提供可重现的示例。
  • 请给出一个可重现的例子。我怀疑你想要的非常非常简单,但是如果不知道你的数据结构、如何生成曲线等,很难说是如何做到的。请阅读How to make a great R reproducible example
  • (a) 不要使用循环。 (b) 使用您用来生成粉色线的任何模型。它应该有一个predict 方法。使用预测增强您的数据,然后执行sum(your_data$y_column &gt; your_data$prediction_column)。如果您需要更多帮助,请发布一个可重现的示例,其中包含一些示例数据和模型代码。

标签: r numbers


【解决方案1】:

使用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)

【讨论】:

    猜你喜欢
    • 2021-12-19
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 2016-03-18
    • 1970-01-01
    • 2016-09-18
    相关资源
    最近更新 更多