[英]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.