# 在特定组内排列值

##### 问题描述投票：1回答：2

``````library(tidyverse)
set.seed(1234)

df <- tibble(group1 = c(rep(LETTERS[1:3], 4)),
group2 = c(rep(0, 6), rep(2, 6)),
value2 = rnorm(12, 20, sd = 10),
value3 = rnorm(12, 20, sd = 50)) %>%
group_by(group1) %>%
mutate(id = c(1:4)) %>%
ungroup()
``````

``````df_nested <- df %>%
group_by(group1, group2) %>%
nest()

# A tibble: 6 x 3
# Groups:   group1, group2 [6]
group1 group2 data
<chr>   <dbl> <list>
1 A           0 <tibble [2 x 3]>
2 B           0 <tibble [2 x 3]>
3 C           0 <tibble [2 x 3]>
4 A           2 <tibble [2 x 3]>
5 B           2 <tibble [2 x 3]>
6 C           2 <tibble [2 x 3]>
``````

``````df_nested %>%
mutate(data = map2_df(.x = data, .y = group2,
~ifelse(.y == 2, arrange(-.x\$id),
.x)))
``````

r dplyr tidyverse purrr
##### 2个回答
1

``````library(dplyr)
library(purrr)

df_nested\$data <- map2(df_nested\$data, df_nested\$group2,~if(.y == 2)
arrange(.x, -.x\$id) else .x)
``````

``````df_nested\$data[[1]]
# A tibble: 2 x 3
#  value2 value3    id
#   <dbl>  <dbl> <int>
#1  13.1  -89.0      1
#2   9.76  -3.29     2
``````

``````df_nested\$data[[4]]
# A tibble: 2 x 3
#value2 value3    id
# <dbl>  <dbl> <int>
#1   15.0  -28.4   4
#2   31.0  -22.8   3
``````

``````map2_df(df_nested\$data, df_nested\$group2,~if(.y == 2) arrange(.x, -.x\$id) else .x)
``````

0

``````df %>%
mutate(id_ = if_else(group2 == 2, id, NA_integer_)) %>%
arrange(group1, group2, -id_)
#> # A tibble: 12 x 6
#>    group1 group2 value2 value3    id   id_
#>    <chr>   <dbl>  <dbl>  <dbl> <int> <int>
#>  1 A           0   17.6  50.2      1    NA
#>  2 A           0   33.8 -14.4      2    NA
#>  3 A           2   23.1  22.6      4     4
#>  4 A           2   13.7  50.2      3     3
#>  5 B           0   15.4  49.9      1    NA
#>  6 B           0   16.2  63.7      2    NA
#>  7 B           2   41.7  -2.90     4     4
#>  8 B           2   16.6  46.7      3     3
#>  9 C           0   19.9 -64.3      1    NA
#> 10 C           0   19.9  59.7      2    NA
#> 11 C           2   34.1  48.5      4     4
#> 12 C           2   32.3  23.1      3     3
```然后，如果需要，我们可以将结果分组并嵌套。```