在`dplyr`输出中添加行 [英] Adding rows in `dplyr` output

查看:124
本文介绍了在`dplyr`输出中添加行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在传统的 plyr 中,返回的行自动添加到输出,即使它们超过了该分组的输入行数:

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

我不知道如何在 dplyr 中做同样的事情。一些尝试:

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.

我该怎么做?

我正在对抗的具体用例是分割一个 \\\
-delimited文本字段并使其长,但是我使用<$ c $

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.

推荐答案

尝试这样:

 dat %>% 
     group_by( g ) %>% 
     do( .[c(1,1,1,2), ] ) %>% 
     ungroup()

这篇关于在`dplyr`输出中添加行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆