【发布时间】:2016-01-27 16:41:38
【问题描述】:
df
patient.ID Index.admission. adm_date dish_date bi
1 124 FALSE 2/7/2009 2/8/2009 0
2 124 TRUE 3/5/2009 3/15/2009 1
3 124 FALSE 4/5/2011 4/7/2011 0
4 124 FALSE 3/25/2012 3/27/2012 0
5 124 TRUE 5/5/2012 5/20/2012 1
6 124 TRUE 9/8/2013 9/15/2013 1
7 124 FALSE 1/5/2014 1/15/2014 0
8 233 FALSE 1/1/2010 1/8/2010 0
9 233 FALSE 1/1/2011 1/5/2011 0
10 233 TRUE 2/2/2011 2/25/2011 1
11 233 FALSE 1/25/2012 1/28/2012 0
12 542 TRUE 3/5/2015 3/15/2015 1
13 1243 TRUE 2/5/2009 2/8/2009 1
14 1243 TRUE 2/5/2011 2/19/2011 1
我需要创建一个新列,将bi 按患者分组。
我的数据应该是这样的:
patient.ID Index.admission. adm_date dish_date bi num_index_ad
1 124 FALSE 2/7/2009 2/8/2009 0 0
2 124 TRUE 3/5/2009 3/15/2009 1 1
3 124 FALSE 4/5/2011 4/7/2011 0 1
4 124 FALSE 3/25/2012 3/27/2012 0 1
5 124 TRUE 5/5/2012 5/20/2012 1 2
6 124 TRUE 9/8/2013 9/15/2013 1 3
7 124 FALSE 1/5/2014 1/15/2014 0 3
8 233 FALSE 1/1/2010 1/8/2010 0 0
9 233 FALSE 1/1/2011 1/5/2011 0 0
10 233 TRUE 2/2/2011 2/25/2011 1 1
11 233 FALSE 1/25/2012 1/28/2012 0 1
12 542 TRUE 3/5/2015 3/15/2015 1 1
13 1243 TRUE 2/5/2009 2/8/2009 1 1
14 1243 TRUE 2/5/2011 2/19/2011 1 2
使用dplyr我有:
df1 <- df %>%
group_by(patient.ID) %>%
for (i in df) {
mutate(num_index_ad = bi[lag(i),] +bi[i,])
}
这会产生错误:“.subset2(x, i, exact = exact) 中的错误:下标越界”
提前致谢:
> dput(df)
structure(list(patient.ID = c(124L, 124L, 124L, 124L, 124L, 124L,
124L, 233L, 233L, 233L, 233L, 542L, 1243L, 1243L), Index.admission. = c(FALSE,
TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, FALSE,
TRUE, TRUE, TRUE), adm_date = structure(c(8L, 10L, 12L, 9L, 13L,
14L, 4L, 1L, 2L, 5L, 3L, 11L, 6L, 7L), .Label = c("1/1/2010",
"1/1/2011", "1/25/2012", "1/5/2014", "2/2/2011", "2/5/2009",
"2/5/2011", "2/7/2009", "3/25/2012", "3/5/2009", "3/5/2015",
"4/5/2011", "5/5/2012", "9/8/2013"), class = "factor"), dish_date = structure(c(7L,
8L, 11L, 10L, 12L, 13L, 1L, 4L, 3L, 6L, 2L, 9L, 7L, 5L), .Label = c("1/15/2014",
"1/28/2012", "1/5/2011", "1/8/2010", "2/19/2011", "2/25/2011",
"2/8/2009", "3/15/2009", "3/15/2015", "3/27/2012", "4/7/2011",
"5/20/2012", "9/15/2013"), class = "factor"), bi = c(0, 1, 0,
0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1)), .Names = c("patient.ID", "Index.admission.",
"adm_date", "dish_date", "bi"), row.names = c(NA, -14L), class = "data.frame")
【问题讨论】:
-
如果您想要
dplyr解决方案,请尝试with(df, ave(bi, patient.ID, FUN = cumsum))或df %>% group_by(patient.ID) %>% mutate(num_index_ad = cumsum(bi))。或查看here 以获得data.table一个 -
@大卫,谢谢你的工作。我仍然不确定为什么我的解决方案不起作用...但感谢您的帮助!
-
子集
bi可能会出现更多错误(您似乎将df$bi视为具有两个维度)但是当使用for(i in df)时,“i”获取“df”每一列的值" 在每次迭代中;见for(i in df) print(i)。