【问题标题】:How to apply a function from a package to a dataframe如何将包中的函数应用到数据框
【发布时间】:2018-10-01 11:09:36
【问题描述】:

如何将包函数应用于数据框?
我有一个包含两列(总计和 n)的数据集(df),我想在其上应用 epitools 包中的 pois.exact 函数(pois.exact(x, pt = 1, conf.level = 0.95))使用 x = df$n 和 pt = df$total f 并获得一个“新”数据框 (new_df),其中包含另外 3 个列以及相应的舍入计算率、下限和上限 CI?

 df <- data.frame("total" = c(35725302,35627717,34565295,36170648,38957933,36579643,29628394,18212075,39562754,1265055), "n" = c(24,66,166,461,898,1416,1781,1284,329,12))


> df
      total    n
1  35725302   24
2  35627717   66
3  34565295  166
4  36170648  461
5  38957933  898
6  36579643 1416
7  29628394 1781
8  18212075 1284
9   9562754  329

事实上,数据框的时间要长得多。 例如,对于第一行,期望的结果是:

require (epitools)
round (pois.exact (24, pt = 35725302, conf.level = 0.95)* 100000, 2)[3:5]
rate lower upper
1 0.07  0.04   0.1

通过应用 pois.exact 函数添加结果的新数据框应如下所示。

 > new_df
     total    n incidence lower_95IC uppper_95IC
1 35725302   24      0.07       0.04        0.10
2 35627717   66      0.19       0.14        0.24
3 34565295  166      0.48       0.41        0.56
4 36170648  461      1.27       1.16        1.40
5 38957933  898      2.31       2.16        2.46
6 36579643 1416      3.87       3.67        4.08
7 29628394 1781      6.01       5.74        6.03
8 18212075 1284      7.05       6.67        7.45
9  9562754  329      3.44       3.08        3.83

谢谢。

【问题讨论】:

  • 不清楚你的问题到底是什么。你试过什么?什么是预期的输出?特别是,pois.exact(df$n, df$total) 不是你想要的?

标签: r function apply


【解决方案1】:
df %>% 
  cbind( pois.exact(df$n, df$total) ) %>%
  dplyr::select( total, n, rate, lower, upper )

#       total    n       rate      lower      upper
# 1  35725302   24 1488554.25 1488066.17 1489042.45
# 2  35627717   66  539813.89  539636.65  539991.18
# 3  34565295  166  208224.67  208155.26  208294.10
# 4  36170648  461   78461.28   78435.71   78486.85
# 5  38957933  898   43383.00   43369.38   43396.62
# 6  36579643 1416   25833.08   25824.71   25841.45
# 7  29628394 1781   16635.82   16629.83   16641.81
# 8  18212075 1284   14183.86   14177.35   14190.37
# 9  39562754  329  120251.53  120214.06  120289.01
# 10  1265055   12  105421.25  105237.62  105605.12

【讨论】:

  • 对于一个简单的调用来说,这是一种不必要的复杂性。
  • @KonradRudolph 是对的,我把事情复杂化了......答案已更新
  • 管道和cbind 仍然是多余的——pois.exact 的输出包含相同的信息。除非 OP 想要重命名列,否则函数调用实际上就是所有需要的。
  • @KonradRudolph我读了 OP 的问题,好像他想在他现有的 df 中“添加”速率,上下限。保留现有的列名。
  • 只要结果相同,这无关紧要。
猜你喜欢
  • 1970-01-01
  • 2021-09-15
  • 2023-03-09
  • 1970-01-01
  • 2016-09-22
  • 1970-01-01
  • 1970-01-01
  • 2020-09-04
  • 2019-04-24
相关资源
最近更新 更多