2

My data looks like this:

library(tidyverse)

set.seed(1)
df <- tibble(
    id = c("cat", "cat", "mouse", "dog", "fish", "fish", "fish"),
    value = rnorm(7, 100, sd = 50)
)

How might I "pop out" the top value of fish, as in move fish to a new data frame and simultaneously remove it from the current data frame?

This works (but it doesn't seem all that elegant):

df_store <- df %>% 
    filter(id == "fish") %>% 
    top_n(1)

df <- anti_join(df, df_store)

Is there a better way?

4

1 回答 1

1

You can do both actions in one single line by using the package pipeR.

library(pipeR); library(dplyr)
df <- df %>>% filter(id == "fish") %>>% top_n(1) %>>% (~ df2) %>% anti_join(df, .)
print(df2)
#### 1  fish 124.3715
print(df)
#### 1 mouse  58.21857
#### 2   dog 179.76404
#### 3  fish  58.97658
#### 4   cat  68.67731
#### 5   cat 109.18217
#### 6  fish 116.47539

I'm no expert of pipeR so you can check it out here, how this kind of assignment within a pipe actually works.

Just one remark: when using top_n i recommend to specify the value column, by default it's the last column but you can easily forget it: top_n(1, value)

于 2016-10-21T12:50:11.290 回答