我有像这样的数据框数据
data
id time var1
1 a 3 0
2 a 2 2
3 a 1 3
4 b 3 2
5 b 4 6
我希望获得每个id的第二大时间行:
data2
id time var1
1 a 2 2
2 b 3 2
我尝试使用sqldf
sqldf("select * from data order by time desc limit 2,1 group by id")
但我收到了错误:
Error in sqliteSendQuery(con, statement, bind.data) :
error in statement: near "group": syntax error
我也试试:
select max(time),* from data where time not in(select max(time) from data group by id) group by id
但我只得到了一个结果,我无法得到正确答案。
谢谢!
答案 0 :(得分:1)
尝试在值小于该id的最大值的行中取最大值:
sqldf("select id, max(time) time, var1
from data a
where time < (select max(b.time)
from data b
where b.id = a.id)
group by id")