【问题标题】:Creating a function to work out oddsratios创建一个函数来计算赔率
【发布时间】:2019-03-25 12:01:35
【问题描述】:

我正在尝试编写一个计算优势比的函数。该函数必须将具有三个变量(“女性”、“男性”和“n”)和四个观察值的数据框作为参数,并返回优势比。

df <- data.frame(female = c("White", "White", "non-White", "non-White"),
                 male = c("White", "non-White", "White", "non-White"),
                 n = c(85, 5, 5, 10))
# data represented as a table
xtabs(n ~ female + male, df)
# the odds ratio here is:
(85 * 10) / (5 * 5) 
#34
MyoddsRatio <- function(df){
  df <- df %>% 
  mutate(oddsratio = (n[1]) * n[4])/(n[2] * n[3]))
return(df)
} 

为了测试该函数是否有效,我希望它返回 34 的赔率。

【问题讨论】:

  • n[1] 之后的括号 ) 不是必需的。您在此处创建列 oddsratio,并返回整个 data.frame。我认为一个值就足够了。
  • 如果您不想在线提问,请不要。目前,除非回答者删除他们的答案,否则无法将其删除。

标签: r function dplyr


【解决方案1】:

如果您的数据框始终采用该格式,您可以使用summarise

library(dplyr)
MyoddsRatio <- function(df) {
  df %>%
    summarise(oddsratio = (n[1] * n[4]) / (n[2] * n[3]))
} 

MyoddsRatio(df)
  oddsratio
1        34

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 2013-01-18
    • 2014-11-05
    • 2014-11-12
    • 2014-07-06
    • 2012-05-11
    相关资源
    最近更新 更多