我有一个tibble结构如下:
day theta
1 1 2.1
2 1 2.1
3 2 3.2
4 2 3.2
5 5 9.5
6 5 9.5
7 5 9.5注意,每个day包含多个行,对于每个day,theta的相同值被重复任意次数。( tibble包含其他任意列,因此需要这种重复结构。)
我想使用dplyr作为theta的累积和值,以便在上面的示例中,2.1只被添加一次到3.2,等等。tibble将被修改,以便附加新的累积和(c.theta)如下:
day theta c.theta
1 1 2.1 2.1
2 1 2.1 2.1
3 2 3.2 5.3
4 2 3.2 5.3
5 5 9.5 14.8
6 5 9.5 14.8
7 5 9.5 14.8
...我最初对group_by day和cumsum over theta所做的努力只导致了对整个数据集(例如2.1 + 2.1 + 3.2 ...)的累积求和,这是不可取的。在我的Stack溢出搜索中,我可以在组内找到许多累积求和的examples,但在组之间却找不到,正如我前面所描述的。如果能朝正确的方向前进,我们将不胜感激。
发布于 2017-10-24 23:25:27
在dplyr中这样做--我想出了一个与PoGibas非常相似的解决方案--使用distinct每天只获得一行,找到和并合并到:
df = read.table(text="day theta
1 1 2.1
2 1 2.1
3 2 3.2
4 2 3.2
5 5 9.5
6 5 9.5
7 5 9.5", header = TRUE)
cumsums = df %>%
distinct(day, theta) %>%
mutate(ctheta = cumsum(theta))
df %>%
left_join(cumsums %>% select(day, ctheta), by = 'day')发布于 2017-10-24 23:17:09
不是dplyr,而是一种替代的data.table解决方案:
library(data.table)
# Original table is called d
setDT(d)
merge(d, unique(d)[, .(c.theta = cumsum(theta), day)])
day theta c.theta
1: 1 2.1 2.1
2: 1 2.1 2.1
3: 2 3.2 5.3
4: 2 3.2 5.3
5: 5 9.5 14.8
6: 5 9.5 14.8
7: 5 9.5 14.8PS:如果您想保留其他列,则必须使用unique(d[, .(day, theta)])
发布于 2017-10-25 12:50:49
在基本R中,可以使用split<-和tapply返回所需的结果。
# construct 0 vector to fill in
dat$temp <- 0
# fill in with cumulative sum for each day
split(dat$temp, dat$day) <- cumsum(tapply(dat$theta, dat$day, head, 1))在这里,tapply返回给cumsum的θ的第一个元素。累积和的元素用split<-给每天喂食。
这会返回
dat
day theta temp
1 1 2.1 2.1
2 1 2.1 2.1
3 2 3.2 5.3
4 2 3.2 5.3
5 5 9.5 14.8
6 5 9.5 14.8
7 5 9.5 14.8https://stackoverflow.com/questions/46921395
复制相似问题