[英]Generate sequence within sub group in data.table
I would like to generate sequence within subgroup columns eg I have two columns id1,val and would like to sort data by id1, val but then generate counter for id1.我想在子组列内生成序列,例如,我有两列 id1、val 并想按 id1、val 对数据进行排序,然后为 id1 生成计数器。
Input输入
input <- data.frame("id1"=c(1,1,1,1,2,2,2),val=c(2,3,4,1,4,3,5))
Expected Output预期产出
id1,val,grp
1,1,1
1,2,2
1,3,3
1,4,4
2,3,1
2,4,2
2,5,3
Previous Reference Posts :以前的参考帖子:
Count for sub group using.grp in data.table 在 data.table 中使用 .grp 对子组进行计数
Numbering rows within groups in a data frame 对数据框中组内的行进行编号
Used below code (I am trying to use code on big data and looking for a solution so I don't need to add an extra step to sort data for "val" column before generating sequence)在代码下方使用(我正在尝试在大数据上使用代码并寻找解决方案,因此我不需要添加额外的步骤来在生成序列之前对“val”列的数据进行排序)
input[, new1:=seq_len(.N), by=c('id1')]
We group by 'id1', sort
the 'val' and then create 'grp' as row_number()
我们按“id1”分组,对“val”
sort
,然后将“grp”创建为row_number()
input %>%
group_by(id1) %>%
mutate(val = sort(val), grp= row_number())
Or another option is to arrange
或者另一种选择是
arrange
input %>%
arrange(id1, val) %>%
group_by(id1) %>%
mutate(grp = row_number())
Or using data.table
或者使用
data.table
library(data.table)
setDT(input)[, c("grp", "val") := .(seq_len(.N), sort(val)), by = id1]
input
# id1 val grp
#1: 1 1 1
#2: 1 2 2
#3: 1 3 3
#4: 1 4 4
#5: 2 3 1
#6: 2 4 2
#7: 2 5 3
If we need to sort as well, use setorder
based on the 'id1' and 'val' to order in place, then create the 'grp' as the rowid
of 'id1'如果我们也需要排序,使用基于'id1'和'val'的
setorder
来排序,然后创建'grp'作为'id1'的rowid
input <- data.frame("id1"=c(1,1,1,1,2,2,2),val=c(2,3,4,1,4,3,5),
achar=c('a','a','b','b','d','c','e'))
setorder(setDT(input), id1, val)[, grp := rowid(id1)][]
# id1 val achar grp
#1: 1 1 b 1
#2: 1 2 a 2
#3: 1 3 a 3
#4: 1 4 b 4
#5: 2 3 c 1
#6: 2 4 d 2
#7: 2 5 e 3
Here's a little factor
hack.这是一个小
factor
黑客。
# Load library
library(data.table)
# Create data table
input <- data.table(id1=c(1,1,1,1,2,2,2),val=c(2,3,4,1,4,3,5))
input[, foo := as.integer(factor(val)), by = "id1"]
# Print result
input
#> id1 val foo
#> 1: 1 2 2
#> 2: 1 3 3
#> 3: 1 4 4
#> 4: 1 1 1
#> 5: 2 4 2
#> 6: 2 3 1
#> 7: 2 5 3
# Reorder for comparison with question
input[order(id1, val)]
#> id1 val foo
#> 1: 1 1 1
#> 2: 1 2 2
#> 3: 1 3 3
#> 4: 1 4 4
#> 5: 2 3 1
#> 6: 2 4 2
#> 7: 2 5 3
Created on 2019-11-29 by the reprex package (v0.3.0)由reprex 包(v0.3.0) 创建于 2019-11-29
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.