Returning first row of group

戏子无情 提交于 2019-11-27 04:41:28
fr3d-5

By reproducing the example data frame and testing it I found a way of getting the needed result:

  1. Order data by relevant columns (ID, Start)

    ordered_data <- data[order(data$ID, data$Start),]

  2. Find the first row for each new ID

    final <- ordered_data[!duplicated(ordered_data$ID),]

As you don't provide any data, here is an example using base R with a sample data frame :

df <- data.frame(group=c("a", "b"), value=1:8)
## Order the data frame with the variable of interest
df <- df[order(df$value),]
## Aggregate
aggregate(df, list(df$group), FUN=head, 1)

EDIT : As Ananda suggests in his comment, the following call to aggregate is better :

aggregate(.~group, df, FUN=head, 1)

If you prefer to use plyr, you can replace aggregate with ddply :

ddply(df, "group", head, 1)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!