鲁棒R函数
基于下面定义的arms,我在鲁棒R函数,r,function,date,dplyr,R,Function,Date,Dplyr,基于下面定义的arms,我在dplyr::mutate函数下编写了这些语句来定义事件。我想知道你是否可以帮我写一个函数,可以减少代码行,因为有些是重复的?谢谢 Arm- 1 (September 1, 2017- August 31, 2018) arm_1_event_1 <- c(as.Date("2017-09-01"), as.Date("2017-11-30")) arm_1_event_2 <- c(as.Date(&quo
dplyr::mutate
函数下编写了这些语句来定义事件。我想知道你是否可以帮我写一个函数,可以减少代码行,因为有些是重复的?谢谢
Arm- 1 (September 1, 2017- August 31, 2018)
arm_1_event_1 <- c(as.Date("2017-09-01"), as.Date("2017-11-30"))
arm_1_event_2 <- c(as.Date("2017-12-01"), as.Date("2018-02-28"))
arm_1_event_3 <- c(as.Date("2018-03-01"), as.Date("2018-05-31"))
arm_1_event_4 <- c(as.Date("2018-06-01"), as.Date("2018-08-31"))
Arm- 2 (September 1, 2018- August 31, 2019)
arm_2_event_1 <- c(as.Date("2018-09-01"), as.Date("2018-11-30"))
arm_2_event_2 <- c(as.Date("2018-12-01"), as.Date("2019-02-28"))
arm_2_event_3 <- c(as.Date("2019-03-01"), as.Date("2019-05-31"))
arm_2_event_4 <- c(as.Date("2019-06-01"), as.Date("2019-08-31"))
Arm- 3 (September 1, 2019- August 31, 2020)
arm_3_event_1 <- c(as.Date("2019-09-01"), as.Date("2019-11-30"))
arm_3_event_2 <- c(as.Date("2019-12-01"), as.Date("2020-02-29"))
arm_3_event_3 <- c(as.Date("2020-03-01"), as.Date("2020-05-31"))
arm_3_event_4 <- c(as.Date("2020-06-01"), as.Date("2020-08-31"))
Arm-1(2017年9月1日-2018年8月31日)
arm_1_event_1您的整个代码(包括第一个块中的赋值)可以简化为一个简单的函数:
arm_和_事件当我们考虑NA时,此函数起作用:
arms_and_events_function <- function(d)
{
df <- data.frame(arm = rep(1:3, each = 4),
event = rep(1:4, 3),
start = as.Date(c("2017-09-01", "2017-12-01", "2018-03-01",
"2018-06-01", "2018-09-01", "2018-12-01",
"2019-03-01", "2019-06-01", "2019-09-01",
"2019-12-01", "2020-03-01", "2020-06-01")),
stop = as.Date(c("2017-11-30", "2018-02-28", "2018-05-31",
"2018-08-31", "2018-11-30", "2019-02-28",
"2019-05-31", "2019-08-31", "2019-11-30",
"2020-02-29", "2020-05-31", "2020-08-31"))
)
sapply(d, function(x) if(is.na(x)) NA else {
inds <- which(x >= df$start & x<= df$stop)
paste0("arm_", df$arm[inds], "_event_", df$event[inds])
})
}
arms\u和\u events\u函数我将此函数应用于所需变量:``arms\u和\u events=arm\u和\u events\u函数(d$date\u application\u received)``我得到了以下错误:df$arm[matches]中的错误:无效的下标类型“列表”您还可以解释一下这一行的作用吗?matches=df$start&x如果在向量中包含缺少的值,则函数不会运行。例如,如果我运行带有日期的函数,我会得到相同的错误。我如何解释使用相同函数时丢失的数据?
arms_and_events_function <- function(d)
{
df <- data.frame(arm = rep(1:3, each = 4),
event = rep(1:4, 3),
start = as.Date(c("2017-09-01", "2017-12-01", "2018-03-01",
"2018-06-01", "2018-09-01", "2018-12-01",
"2019-03-01", "2019-06-01", "2019-09-01",
"2019-12-01", "2020-03-01", "2020-06-01")),
stop = as.Date(c("2017-11-30", "2018-02-28", "2018-05-31",
"2018-08-31", "2018-11-30", "2019-02-28",
"2019-05-31", "2019-08-31", "2019-11-30",
"2020-02-29", "2020-05-31", "2020-08-31"))
)
sapply(d, function(x) if(is.na(x)) NA else {
inds <- which(x >= df$start & x<= df$stop)
paste0("arm_", df$arm[inds], "_event_", df$event[inds])
})
}