【问题标题】:Adding rows in `dplyr` output在 `dplyr` 输出中添加行
【发布时间】:2014-06-30 13:00:01
【问题描述】:

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

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 中做同样的事情。一些尝试:

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.

我该怎么做?

我反对的具体用例是拆分\n-delimited 文本字段并将其设置为“长”,但我一直将ddply 的此功能用于多种目的。

【问题讨论】:

    标签: r dplyr split-apply-combine


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • 我收到Error: object of type 'closure' is not subsettable。但是do( function(d) d[c(1,1,1,2), ] ) %&gt;% taRifx::stack.list() 有效....
    • 从 github 安装最新的 dplyr。
    • 稍后检查,谢谢。我安装了最新发布的版本,但没有安装 github 版本。
    猜你喜欢
    • 2020-07-11
    • 1970-01-01
    • 2018-03-22
    • 2016-08-19
    • 1970-01-01
    • 2017-01-23
    • 2018-05-03
    • 2022-12-11
    • 2023-02-10
    相关资源
    最近更新 更多