总结R数据框中的值

时间:2015-02-04 20:42:34

标签: r

假设我在R中有一个看起来像这样的数据框......

Time    Event
1       0
1       1
1       0
2       0
2       0
3       0
3       1
3       0
3       1
3       0

在这个数据框架上,我想获得另一个带有几个汇总值的数据框。我想要原始时间,时间等于或大于所讨论时间的行数,以及当时发生的事件数。

示例输出:

Time    Eligible    Event
1       10          1
2        7          0
3        5          2

我已尝试使用matchbytable功能来完成此任务,但我无法做任何事情。我可以做一个双for循环...但是必须有更好的方法。

我该怎么做?我想在基地R中这样做,而不是使用plyr或其他一些图书馆...

3 个答案:

答案 0 :(得分:2)

仅使用base R,我们可以使用lapply循环播放唯一的“时间”,根据所描述的条件获取摘要统计信息。

 res <- do.call(rbind,lapply(unique(df$Time), function(x) 
          data.frame(Time=x, Eligible=sum(x<=df$Time),
                Event=sum(df$Event[df$Time %in%x]))))

 res
 #  Time Eligible Event
 #1    1       10     1
 #2    2        7     0
 #3    3        5     2

数据

 df <- structure(list(Time = c(1L, 1L, 1L, 2L, 2L, 3L, 3L, 3L, 3L, 3L
 ), Event = c(0L, 1L, 0L, 0L, 0L, 0L, 1L, 0L, 1L, 0L)), .Names = c("Time", 
"Event"), class = "data.frame", row.names = c(NA, -10L))

答案 1 :(得分:0)

您可以将tapply用于同一效果

newData <- data.frame(
    Eligible = tapply(myData$Event,myData$Time,length),
    Events = tapply(myData$Event,myData$Time,sum))

如果您有多个摘要,则lapply可以覆盖data.frame的字段。

答案 2 :(得分:0)

也许这可以解释一下:

countEligible <- function(x, Time) {

  sum(x <= Time)

}

dat1 <- data.frame(Time = unique(dat$Time), Eligible = unique(sapply(dat$Time, function(x) countEligible(x, dat$Time))))

dat2 <- data.frame(Time = unique(dat$Time), Event = tapply(dat$Event, dat$Time, sum))

merge(dat1, dat2)

> merge(dat1, dat2)
  Time Eligible Event
1    1       10     1
2    2        7     0
3    3        5     2
相关问题