R:使用dplyr函数创建函数

时间:2016-02-29 20:57:59

标签: r dplyr

我有一个包含三个感兴趣变量的数据框:

  • 生存时间
  • 分组因素
  • 事件指示器(死亡:是或否)

我想计算每组的发病率。我每天都这样做,所以有一个函数执行此操作而不是长脚本会很棒。

我已尝试过以下操作,但无法正常工作。

library(survival)
data(lung) # example data
lung$death <- ifelse(lung$status==1, 0, 1) # event indicator: 0 = survived; 1 = dead.

# Function
func <- function(data_frame, group, survival_time, event) {
     library(epitools)
     table <- data_frame %>%
          filter_(!is.na(.$group)) %>%
          group_by_(.$group) %>%
          summarise_(pt = round(sum(as.numeric(.$survival_time)/365.25)),
                     events = sum(.$event)) %>%
          do(pois.exact(.$events, pt = .$pt/1000, conf.level = 0.95)) %>%
          ungroup() %>%
          transmute_(Category = c(levels(as.factor(.$group))),
                     Events = x,
                     Person_years = pt*1000,
                     Incidence_Rate = paste(format(round(rate, 2), nsmall=2), " (",
                                      format(round(lower, 2), nsmall=2), " to ",
                                      format(round(upper, 2), nsmall=2), ")", 
                                      sep=""))
     return(table)
}

func(lung, sex, time, death)

**Error: incorrect length (0), expecting: 228 In addition: Warning message:
In is.na(.$group) : is.na() applied to non-(list or vector) of type 'NULL'**

有什么想法吗?我在dplyr上读过关于NSE和SE的帖子,但是我认为我正确地应用了这些建议?

1 个答案:

答案 0 :(得分:2)

以下是解决方案的一部分

data_frame = lung
group = "sex"
survival_time = "time"
event = "death"
data_frame %>%
  filter_(paste("!is.na(", group, ")")) %>%
  group_by_(group) %>%
  summarise_(
    pt = paste("round(sum(as.numeric(", survival_time, ") / 365.25))"),
    events = paste("sum(", event, ")")
  )