将函数应用于dataframe的每一列

将函数应用于dataframe的每一列,r,apply,R,Apply,我有以下(非常大的)数据帧: id epoch 1 0 1.141194e+12 2 1 1.142163e+12 3 2 1.142627e+12 4 2 1.142627e+12 5 3 1.142665e+12 6 3 1.142665e+12 7 4 1.142823e+12 8 5 1.143230e+12 9 6 1

我有以下(非常大的)数据帧:

     id         epoch
1     0     1.141194e+12
2     1     1.142163e+12
3     2     1.142627e+12
4     2     1.142627e+12
5     3     1.142665e+12
6     3     1.142665e+12
7     4     1.142823e+12
8     5     1.143230e+12
9     6     1.143235e+12
10    6     1.143235e+12
对于每个唯一的ID,我现在想要得到它的最大时间和最小时间(历元时间戳)之间的差异。如果相关的话,有比上面示例中更多的ID出现。我还没有在R上做过很多工作,尝试了以下方法:

unique = data.frame(as.numeric(unique(df$id)))
differences = apply(unique, 1, get_duration)

get_duration = function(id) {
  maxTime = max(df$epoch[which(df$id == id)])
  minTime = min(df$epoch[which(df$id == id)])
  return ((maxTime - minTime) / 1000)
}

它可以工作,但速度非常慢。什么是更快的方法?

只需按id使用一次过滤器

subset = df$epoch[which(df$id == id)]
maxTime = max(subset)
minTime = min(subset)

有几种方法。在base
R
中:

tapply(df$epoch,df$id,function(x) (max(x)-min(x))/1000)
带有
数据。表

require(data.table)
setDT(df)
df[,list(d=(max(epoch)-min(epoch))/1000),by=id]

这可以在
dplyr中轻松完成

require(dplyr)
df %>% group_by(id) %>% summarize(diff=(max(epoch)-min(epoch))/1000)

请注意,您正在隐藏您也使用的
unique
函数。这是需要小心和避免的。检查现有的
conflicts()
。另外
tapply(df$epoch,df$id,function(x)max(x)-min(x))
@nicola实际上不是
tapply(df$epoch,df$id,function(x)(max(x)-min(x))/1000)
来匹配OP的原始函数吗?@Tgsmith61591是的,我想你是对的。另一种方法是使用
data.table
setDT(df);df[,list(d=(max(epoch)-min(epoch))/1000),by=id]
谢谢,tapply就是我要找的!但是,我不明白你隐藏唯一函数的意思-你能更详细地解释一下吗?这是一个优化,但没有上面使用
apply
系列的一些注释那么大<这里的答案是code>tapply