Adding rows in `dplyr` output
Asked Answered
E

1

6

In traditional plyr, returned rows are added automagically to the output even if they exceed the number of input rows for that grouping:

set.seed(1)
dat <- data.frame(x=runif(10),g=rep(letters[1:5],each=2))
> ddply( dat, .(g), function(df) df[c(1,1,1,2),] )
            x g
1  0.26550866 a
2  0.26550866 a
3  0.26550866 a
4  0.37212390 a
5  0.57285336 b
6  0.57285336 b
7  0.57285336 b
8  0.90820779 b
9  0.20168193 c
10 0.20168193 c
11 0.20168193 c
12 0.89838968 c
13 0.94467527 d
14 0.94467527 d
15 0.94467527 d
16 0.66079779 d
17 0.62911404 e
18 0.62911404 e
19 0.62911404 e
20 0.06178627 e

I cannot figure out how to do the same in dplyr. Some attempts:

dat %>% group_by(g) %>% summarise( xbar = mean(x) )

> dat %>% group_by(g) %>% summarise( xbar = runif(3) )
Error: expecting a single value

# Getting creative...

> dat %>% group_by(g) %>% function(x) x[c(1,1,1,2),]

# Nope.

How do I do this?

The specific use case I'm butting up against is splitting a \n-delimited text field and making it "long," but I use this feature of ddply all the time for many purposes.

Embower answered 13/5, 2014 at 1:10 Comment(0)
A
7

Try this:

 dat %>% 
     group_by( g ) %>% 
     do( .[c(1,1,1,2), ] ) %>% 
     ungroup()
Arlaarlan answered 13/5, 2014 at 10:35 Comment(3)
I get Error: object of type 'closure' is not subsettable. But do( function(d) d[c(1,1,1,2), ] ) %>% taRifx::stack.list() works....Embower
Install the latest dplyr from github.Arlaarlan
Will check later, thanks. I have the latest released version installed but not the github version.Embower

© 2022 - 2024 — McMap. All rights reserved.