创建一个计算出赔率的函数

时间:2019-03-25 12:01:35

标签: r function dplyr

我正在尝试编写一个计算比值比的函数。该函数必须将具有三个变量(“ female”,“ male”和“ 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的比值比。

1 个答案:

答案 0 :(得分:1)

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

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

MyoddsRatio(df)
  oddsratio
1        34