我一直在尝试通过查看其他帖子来处理我的数据,但我不断收到错误。我的数据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
From 选择包含 R 中每日最大值的行我尝试了以下方法但没有成功
ddply(new,~id,function(x){x[which.max(new$year),]})
我也尝试过
tapply(new$year, new$id, max)
但这并没有给我想要的输出。
任何建议都会很有帮助!
对于大型表来说,另一个可以很好扩展的选项是使用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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)