[英]Aggregate multiple rows of the same data.frame in R based on common values in given columns
[英]Combing data frame rows in R based on common values
給定一個數據框:
> df <- data.frame( L=c('a','b','b'), t0=c(1,10,20), t1=c(9,19,39))
> df
L t0 t1
1 a 1 9
2 b 10 19
3 b 20 39
I want:
> df
L t0 t1
1 a 1 9
2 b 10 39
df$L 的相同值等於 "b" 表示 'b' 第一個實例的開始 (t0) 應該是新的 't0' 值和 (contiguous) ' 最后一個實例的新 't1' 值b' 應該是新的 't1' 值。 實際上,如果 t0 和 t1 是時間,那么我想合並具有相同“L”值的相鄰行的持續時間。
通過“L”分組后, summarise
采取first
“T0”和的值last
的“T1”的值(或min
和max
)
df %>%
group_by(L) %>%
summarise(t0 = first(t0), t1 = last(t1))
# A tibble: 2 x 3
# L t0 t1
# <fct> <dbl> <dbl>
#1 a 1 9
#2 b 10 39
根據 OP 的評論,如果我們還按“L”中相鄰的相似元素進行分組,請使用rleid
library(data.table)
df1 %>%
group_by(grp = rleid(L), L) %>%
summarise(t0 = first(t0), t1 = last(t1))
df1 <- data.frame( L=c('a','b','b','a','b','b'),
t0=c(1,10,20,40,60,70), t1=c(9,19,39,49,69,79))
您可以按L
split
並返回range
。
df <- do.call(rbind, lapply(split(df[-1], df[1]), range))
df
# [,1] [,2]
#a 1 9
#b 10 39
df <- data.frame(L=rownames(df), t0=df[,1], t1=df[,2])
df
# L t0 t1
#a a 1 9
#b b 10 39
也許你可以嘗試aggreate
和merge
res <- merge(aggregate(t0 ~ L,df,min),aggregate(t1 ~ L,df,max))
以至於
> res
L t0 t1
1 a 1 9
2 b 10 39
使用data.table
:
library(data.table)
setDT(df)
df[, .(t0 = t0[1], t1 = t1[.N]), by = L]
# L t0 t1
# 1: a 1 9
# 2: b 10 39
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.