按组选择最大行值

3

我一直在尝试通过查看其他帖子来处理我的数据,但是我一直遇到错误。我的数据 new 看起来像这样:

id  year    name    gdp
1   1980    Jamie   45
1   1981    Jamie   60
1   1982    Jamie   70
2   1990    Kate    40
2   1991    Kate    25
2   1992    Kate    67
3   1994    Joe     35
3   1995    Joe     78
3   1996    Joe     90

我希望通过id选择年份值最高的行。因此,我们需要输出以下内容:
id  year    name    gdp
1   1982    Jamie   70
2   1992    Kate    67
3   1996    Joe     90

我从选择包含每日最大值的行中尝试了以下操作,但并没有起作用

ddply(new,~id,function(x){x[which.max(new$year),]})

我也尝试过。
tapply(new$year, new$id, max)

但是这并没有给我想要的输出结果。 任何建议都将非常有帮助!
5个回答

3

对于大型表格,另一个可扩展的选择是使用 data.table

DT <- read.table(text = "id  year    name    gdp
                          1   1980    Jamie   45
                          1   1981    Jamie   60
                          1   1982    Jamie   70
                          2   1990    Kate    40
                          2   1991    Kate    25
                          2   1992    Kate    67
                          3   1994    Joe     35
                          3   1995    Joe     78
                          3   1996    Joe     90",
                 header = TRUE)

require("data.table")
DT <- as.data.table(DT)

setkey(DT,id,year)
res = DT[,j=list(year=year[which.max(gdp)]),by=id]
res

setkey(res,id,year)
DT[res]
# id year  name gdp
# 1:  1 1982 Jamie  70
# 2:  2 1992  Kate  67
# 3:  3 1996   Joe  90

2

只需使用 split

df <- do.call(rbind, lapply(split(df, df$id),
  function(subdf) subdf[which.max(subdf$year)[1], ]))

例如,
df <- data.frame(id = rep(1:10, each = 3), year = round(runif(30,0,10)) + 1980, gdp = round(runif(30, 40, 70)))
print(head(df))
#   id year gdp
# 1  1 1990  49
# 2  1 1981  47
# 3  1 1987  69
# 4  2 1985  57
# 5  2 1989  41
# 6  2 1988  54

df <- do.call(rbind, lapply(split(df, df$id), function(subdf) subdf[which.max(subdf$year)[1], ]))
print(head(df))
#    id year gdp
# 1   1 1990  49
# 2   2 1989  41
# 3   3 1989  55
# 4   4 1988  62
# 5   5 1989  48
# 6   6 1990  41

1
说实话,这对于这个任务来说似乎过于复杂了。你本质上是在用 split+lapply 重新创建 by - thelatemail

2
您可以使用duplicated来完成此操作。
# your data
 df <- read.table(text="id  year    name    gdp
1   1980    Jamie   45
1   1981    Jamie   60
1   1982    Jamie   70
2   1990    Kate    40
2   1991    Kate    25
2   1992    Kate    67
3   1994    Joe     35
3   1995    Joe     78
3   1996    Joe     90" , header=TRUE)

# Sort by id and year (latest year is last for each id)
df <- df[order(df$id , df$year), ]

# Select the last row by id
df <- df[!duplicated(df$id, fromLast=TRUE), ]

2
< p > ave 再次发挥作用,并将考虑具有多行的情况,以获得最大年份。

new[with(new, year == ave(year,id,FUN=max) ),]

#  id year  name gdp
#3  1 1982 Jamie  70
#6  2 1992  Kate  67
#9  3 1996   Joe  90

1

你的ddply实现看起来不错,但是你在回调函数中引用了原始数据集。

ddply(new,~id,function(x){x[which.max(new$year),]})
# should be
ddply(new,.(id),function(x){x[which.max(x$year),]})

2
似乎应该选择这个答案。 - IRTFM

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接