R:如何从每个组中获取最后一个元素? [英] R: How to get the last element from each group?

查看:230
本文介绍了R:如何从每个组中获取最后一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含时间序列的数据框,该时间序列带有两个时间戳列,分别是 d $ day d $ time ,并且为简单起见,假设一个测量变量 d $ val1

I have a data frame containing a time series with two time stamp columns, d$day and d$time, and say, for simplicity, one measured variable d$val1.

假设我要检查这种情况在每天实验结束时(即最后一次测量)(如果有的话)。 (并非每天都有测量值,并且每天都可以在不同时间进行测量。)

Suppose I want to examine the situation at the close of each day's experiment, i.e. the last measurement, if it exists. (Not every day has a measurement, and measurements can be taken at different times each day.)

我希望能够通过进行汇总一天并在<$上使用某种 last() tail()函数c $ c> time 来拉回相应的 val

I would like to be able to aggregate by day and use some sort of last() or tail() function on time to pull back the corresponding val.

尝试过这样的变体,但收效甚微(一个问题是,尾部需要一个参数,但如何在总计中指定该参数?)

I've tried variations like this with not much success (one issue is that tail requires an argument, but how to specify that within aggregate?)

 val_eod <- aggregate(d$val1, by=list(d$day), FUN=tail(...))

有没有更简单的方法?

推荐答案

您尝试过吗?

val_eod <- aggregate(d$val1, by = list(d$day), FUN = tail, n = 1)

这篇关于R:如何从每个组中获取最后一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆