如何在R中查找面板数据集中的第一个和最后一个引用
我有一张桌子:如何在R中查找面板数据集中的第一个和最后一个引用,r,R,我有一张桌子: id time 1 1 1 2 1 5 2 3 2 2 2 7 3 8 3 3 3 14 我想把它转换成: id first last 1 1 5 2 3 7 3 8 14 请帮忙 我们可以使用数据表。将“data.frame”转换为“data.table”(setDT(df1)),按“id”分组,我们得到“time”的第一个和最后一个值 library(data.table) set
id time
1 1
1 2
1 5
2 3
2 2
2 7
3 8
3 3
3 14
我想把它转换成:
id first last
1 1 5
2 3 7
3 8 14
请帮忙 我们可以使用
数据表。将“data.frame”转换为“data.table”(setDT(df1)
),按“id”分组,我们得到“time”的第一个和最后一个值
library(data.table)
setDT(df1)[, list(firstocc = time[1L], lastocc = time[.N]),
by = id]
或者对于dplyr
,我们使用相同的方法
library(dplyr)
df1 %>%
group_by(id) %>%
summarise(firstocc = first(time), lastocc = last(time))
或使用基本R
(无需软件包)
如果我们需要基于min
和max
值(与预期输出无关),则data.table
选项为
setDT(df1)[, setNames(as.list(range(time)),
c('firstOcc', 'lastOcc')) ,id]
并且dplyr
df1 %>%
group_by(id) %>%
summarise(firstocc = min(time), lastocc = max(time))
在R中有许多包可以执行这种类型的聚合。我们展示了如何在没有任何包的情况下进行聚合,然后用一些包进行展示
1)使用aggregate
。不需要软件包
ag <- aggregate(time ~ id, DF, function(x) c(first = min(x), last = max(x)))
ag
是一个两列数据框,其第二列包含一个两列矩阵,其中列名为“first”和“last”。如果要将其展平为3列数据帧,请使用:
do.call("cbind", ag)
给予:
> ag
id time.first time.last
1 1 1 5
2 2 2 7
3 3 3 14
id first last
[1,] 1 1 5
[2,] 2 2 7
[3,] 3 3 14
id first last
[1,] 1 1 5
[2,] 2 2 7
[3,] 3 3 14
id time.min time.max
1 1 1 5
2 2 2 7
3 3 3 14
1a)第(1)项的这种变体更紧凑,但以更难看的列名为代价
aggregate(time ~ id, DF, range)
2)sqldf
library(sqldf)
sqldf("select id, min(time) first, max(time) last from DF group by id")
给予:
> ag
id time.first time.last
1 1 1 5
2 2 2 7
3 3 3 14
id first last
[1,] 1 1 5
[2,] 2 2 7
[3,] 3 3 14
id first last
[1,] 1 1 5
[2,] 2 2 7
[3,] 3 3 14
id time.min time.max
1 1 1 5
2 2 2 7
3 3 3 14
3)数据包中的summaryBysummaryBy很像aggregate
:
library(doBy)
summaryBy(time ~ id, data = DF, FUN = c(min, max))
给予:
> ag
id time.first time.last
1 1 1 5
2 2 2 7
3 3 3 14
id first last
[1,] 1 1 5
[2,] 2 2 7
[3,] 3 3 14
id first last
[1,] 1 1 5
[2,] 2 2 7
[3,] 3 3 14
id time.min time.max
1 1 1 5
2 2 2 7
3 3 3 14
注意:以下是可复制形式的输入DF
:
Lines <- "id time
1 1
1 2
1 5
2 3
2 2
2 7
3 8
3 3
3 14"
DF <- read.table(text = Lines, header = TRUE)
行您可以删除重复项并对其进行重塑
dd <- read.table(header = TRUE, text = "id time
1 1
1 2
1 5
2 3
2 2
2 7
3 8
3 3
3 14")
d2 <- dd[!(duplicated(dd$id) & duplicated(dd$id, fromLast = TRUE)), ]
reshape(within(d2, tt <- c('first', 'last')), dir = 'wide', timevar = 'tt')
# id time.first time.last
# 1 1 1 5
# 4 2 3 7
# 7 3 8 14
dd按id分组时的可能重复项我不想订购id。我想按它的顺序订购。你能帮我吗?@PreetRajdeo你可以将“id”转换成因子类,并按相同的顺序设置等级。i、 e.df1%>%group_by(id=系数(id,级别=唯一(id)))%>%summary(firstocc=min(时间),lastocc=max(时间))