【发布时间】:2016-07-25 03:49:00
【问题描述】:
我想根据组 变量用户和真假创建一个计数器变量c 变量B。
DT <- data.table(time=c(1,2,3,1,1,2,3,1,1,1),user=c(1,1,1,2,3,3,3,4,4,5), B=c('t','f','t','f','f','t','t','t','t','t'))
DT
变量c的期望输出
time user B C
1: 1 1 t 1
2: 2 1 f 1
3: 3 1 t 2
4: 1 2 f 0
5: 1 3 f 0
6: 2 3 t 1
7: 3 3 t 2
8: 1 4 t 1
9: 2 4 t 2
10: 1 5 t 1
当 B 为真时,变量 c 是组内的计数器。 变量c的逻辑(非代码)如下。从时间变量中可以看出,顺序确实很重要。
if time=1 and b=='f' {c=0}
else
{
if b=='t'{c=previous[c]+1}
else {c=previous[c]}
}
#if there is no variable b, the counter can be created using dplyr:
group_by(user)%>%mutate(c=seq_along(user))
#or data.table
DT[, c := seq_len(.N), by = user]
# we can use data.table function shift() combined with for loop but i want to avoid for loop, it is slow and I have 300,000 rows.
【问题讨论】:
-
您应该将 B 存储为逻辑向量,而不是使用您自己的真假代码。试试
DT[, B := B == "t"] -
我对你的代码有点迷茫。您将 B 存储为逻辑,对吗?@Frank
-
代码用
class或logical覆盖您的B 列。如果您不清楚我的意思,请阅读?class和?logical的文档。 -
“在每组用户中创建一个 B==True 的累积计数器”
标签: r data.table dplyr