我想计算在整洁的 data.table 中每个组有多少个 TRUE 标记:
DT <- data.table( id = c(1 ,1 ,1 ,2 ,2 ,2 ,2 ,2 )
, marker = c(TRUE,FALSE,FALSE,TRUE,FALSE,TRUE,TRUE,FALSE))
Run Code Online (Sandbox Code Playgroud)
所以我尝试了DT[marker==TRUE, num_markers := .N, by = id],输出:
id marker num_markers
1: 1 TRUE 1
2: 1 FALSE NA
3: 1 FALSE NA
4: 2 TRUE 3
5: 2 FALSE NA
6: 2 TRUE 3
7: 2 TRUE 3
8: 2 FALSE NA
Run Code Online (Sandbox Code Playgroud)
相反,所需的输出是:
id marker num_markers
1: 1 TRUE 1
2: 1 FALSE 1
3: 1 FALSE 1
4: 2 TRUE 3
5: 2 FALSE 3
6: 2 TRUE 3
7: 2 TRUE 3
8: 2 FALSE 3
Run Code Online (Sandbox Code Playgroud)
如何调整代码以获得所需的输出(删除每个 id 的 NA 并填写标记组数?)
也许在标记列上使用sum :
DT[, num_markers := sum(marker), by = id ][]
# id marker num_markers
# 1: 1 TRUE 1
# 2: 1 FALSE 1
# 3: 1 FALSE 1
# 4: 2 TRUE 3
# 5: 2 FALSE 3
# 6: 2 TRUE 3
# 7: 2 TRUE 3
# 8: 2 FALSE 3
Run Code Online (Sandbox Code Playgroud)