计算经过的“时间",其中参考时间取决于因素 [英] Calculate elapsed "times", where the reference time depends on a factor

查看:109
本文介绍了计算经过的“时间",其中参考时间取决于因素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算数据帧中的经过时间,其中经过时间的开始"值取决于数据帧中因子列的值. (简单来说,我将时间值视为数字而不是时间对象-我的问题是关于拆分应用合并,而不是时间对象).我的数据框如下所示:

I'm trying to calculate elapsed times in a data frame, where the 'start' value for the elapsed time depends on the value of a factor column in the data frame. (To simply the question, I'll treat the time values as numeric rather than time objects - my question is about split-apply-combine, not time objects). My data frame looks like this:

df <- data.frame(id=gl(2, 3, 5, labels=c("a", "b")), time=1:5)

我想通过从每次时间中减去每个因子水平中的最小时间来计算经过时间(尽管对于本示例,我只处理数字值,而不是时间值).因此,我想将数据帧除以id,从y列中的每个元素中减去最小的y值,然后返回具有转换后值的向量(或数据帧).我想结束的事情是这样的:

I'd like to calculate elapsed times by subtracting the minimum time in each factor level from each time (although for the sake of this example I'll just deal with numeric values, not time values). So I'd like to split the data frame by id, subtract the minimum y value from each element in the y column, and return a vector (or data frame) with the transformed values. I want to end up with something like:

> dfTrans
id  time  elapsed
a      1        0
a      2        1
a      3        2
b      4        0
b      5        1   

对于plyr来说似乎是一项完美的任务,但我找不到简单的解决方案.

Seems like a perfect task for plyr, but I can't find a simple solution.

我能想到的最好的是

elapsed <- dlply(df, .(id), function(x) x$time - min(x$time))
elapsed_comb <- NA
for(i in 1:length(names(elapsed))) {
  elapsed_comb <- c(elapsed_comb, elapsed[[i]])
}
elapsed_comb <- elapsed_comb[-1]
df$elapsed <- elapsed_comb

这很不雅观,而且似乎很脆弱.当然有更好的方法吗?

This is inelegant, and seems fragile. Surely there's a better way?

推荐答案

当结果是一个长度与数据帧中的行数相同的向量时,首先要考虑的是'ave'函数:

The 'ave' function is the first thing you should think of when the results is to be a vector with the same length as the number of rows in the dataframe:

 df$elapsed <- ave(df$time, df$id, FUN=function(x) x -min(x) )
 df
  id time elapsed
1  a    1       0
2  a    2       1
3  a    3       2
4  b    4       0
5  b    5       1

这篇关于计算经过的“时间",其中参考时间取决于因素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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