[R] selecting first row of a variable with long-format data

Dennis Murphy djmuser at gmail.com
Mon Sep 26 04:10:04 CEST 2011


Hi:

The head() function is helpful here:

(i) plyr::ddply()

library('plyr')
ddply(dat, .(id), function(d) head(d, 1))
  id value
1  1     5
2  2     4

(ii) aggregate():
aggregate(value ~ id, data = dat, FUN = function(x) head(x, 1))
  id value
1  1     5
2  2     4

The formula version of aggregate() requires R-2.11.0 +

Dennis

On Sun, Sep 25, 2011 at 1:22 PM, AC Del Re <delre at wisc.edu> wrote:
> Hi,
>
> I am trying to select the first row of a variable with data in long-format,
> e.g.,
>
> # sample data
> id <- c(1,1,1,2,2)
> value <- c(5,6,7,4,5)
> dat <- data.frame(id, value)
> dat
>
> How can I select/subset the first 'value'  for each unique 'id'?
>
> Thanks,
>
> AC
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list