如何在 R 中编写代码以计算 R 中特定年龄的特定序列

how write codes In R to calculate specific sequence in R for specific age

提问人:Azam Mirzaei 提问时间:9/16/2023 最后编辑:Azam Mirzaei 更新时间:9/18/2023 访问量:79

问:

我有一个数据集,如下所示:

     library("tidyverse")
     DataSet2<-
     tibble(
     id = c(1,2,3,4,5,6,7,8,9,10),
     AGE=  c(15,15.25,15.5, 15.75, 16, 16.25, 16.5, 16.75, 46.5, 46.75),
     f_curve_notch= c(25.14,30.28,43.33,43.33,25.14,25.14,25.14,25.14,67   
     ,33.77),
     f_curve_tilde= 
                  c(.2514,30.28,43.33,43.33,25.14,25.14,25.14,25.14,.67   
     ,33.77),
      )

我想在 R 中计算 100 万个人的后续公式:第一个和最后一个公式与其他组不同。

    age15probarea=((f_curve_notch(age15)*2)+ 
    (f_curve_notch(age15.25)*2)+f_curve_notch(age15.5)/5.

    age16probarea=(f_curve_notched(age15.5)+ 
    (f_curve_notch(age15.75)*2)+ 
    (f_curve_notch(age16)*2)+ 
    (f_curve_notch(age16.25)*2)+f_curve_notch(age16.5)/8.
     ......

这个过程必须持续到 46.5,尽管我只提供一些年龄的信息 而对于最后一个时代,

       age47probarea=(f_curve_notch(age46.5+ 
       (f_curve_notch(age46.75*2))/3.

在下一步中:我想用一个条件来计算这个公式,如果特定年龄的f_cureve_nutched大于零且不等于相同年龄f_curve_tilde,则 f_curve_tilde - f_curve_notched else 是 age16probarea 的前一个金额:

    DataSet$age16probarea<-   ifelse ((f_curve_notch(age15.5)>0 
    &  f_curve_notch(age15.75) != f_curve_tilde(age15.75),
    age16probarea+ ((f_curve_tilde(age15.75) - 
     f_curve_notch(age15.75))*0.125), age16probarea)
R 函数 循环 data.table mutate

评论

2赞 Jon Spring 9/16/2023
这似乎是一个相关的问题,如果不是同一个问题:stackoverflow.com/questions/77029088/......
1赞 Azam Mirzaei 9/16/2023
亲爱的@JonSpring,感谢您的评论。是的,这个问题与此有关,但与上一个过程有关。我正在编写代码来计算女性的出生史,并逐步询问有关该程序的问题。但是,这个问题与您提到的问题有一些不同
2赞 Mark 9/16/2023
嗨,阿扎姆!你的 tibble 不会运行,因为有重复的名称
2赞 Mark 9/16/2023
另外,只是仔细检查 - 是要除以 8 吗?看起来你正在做一个加权平均值,但显然,如果第一个点有 5 个点,加权平均值将被抛弃,但它被除以 8age15probarea
3赞 Mark 9/16/2023
@AzamMirzaei您的代码引用了各个年龄的列,例如 f_curve_notched_age18.5,但您的示例 DataFrame 没有这个

答:

1赞 Mohammad Haddadi 9/18/2023 #1

我想你正在寻找铅功能:

     DataSet2<-DataSet2 %>%
     mutate(prob = (f_curve_notch + 2 * lead(f_curve_notch) + 2 * 
     lead(f_curve_notch, 2) + 2 * lead(f_curve_notch, 3) + lead(f_curve_notch, 
      4))/8) %>%
      as.data.frame()