[英]Generate sequence of numbers increasing after n rows by group in R data.table
[英]Generate sequence within sub group in data.table
我想在子组列内生成序列,例如,我有两列 id1、val 并想按 id1、val 对数据进行排序,然后为 id1 生成计数器。
输入
input <- data.frame("id1"=c(1,1,1,1,2,2,2),val=c(2,3,4,1,4,3,5))
预期产出
id1,val,grp
1,1,1
1,2,2
1,3,3
1,4,4
2,3,1
2,4,2
2,5,3
以前的参考帖子:
在代码下方使用(我正在尝试在大数据上使用代码并寻找解决方案,因此我不需要添加额外的步骤来在生成序列之前对“val”列的数据进行排序)
input[, new1:=seq_len(.N), by=c('id1')]
我们按“id1”分组,对“val” sort
,然后将“grp”创建为row_number()
input %>%
group_by(id1) %>%
mutate(val = sort(val), grp= row_number())
或者另一种选择是arrange
input %>%
arrange(id1, val) %>%
group_by(id1) %>%
mutate(grp = row_number())
或者使用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
如果我们也需要排序,使用基于'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
这是一个小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
由reprex 包(v0.3.0) 创建于 2019-11-29
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.