簡體   English   中英

r-將dplyr :: group_by與purrr :: pmap結合使用

[英]r - use dplyr::group_by in combination with purrr::pmap

我有以下數據框:

df <- data.frame(a = c(1:20),
             b = c(2:21),
             c = as.factor(c(rep(1,5), rep(2,10), rep(3,5))))

我想執行以下操作:

df1 <- df %>% group_by(c) %>% mutate(a = lead(b))

但是最初我有很多變量,需要將lead()函數與group_by()結合應用於多個變量。 我正在嘗試purrr::pmap()實現此目的:

df2 <- pmap(list(df[,1],df[,2],df[,3]), function(x,y,z) group_by(z) %>% lead(y))

不幸的是,這導致錯誤:

 Error in UseMethod("group_by_") : 
  no applicable method for 'group_by_' applied to an object of class "c('integer', 'numeric')"

您可以使用mutate_atmutate_at funs()命名參數來執行此操作,這將創建新列而不是覆蓋它們。 請注意,此操作對a無效,但是您可以根據需要在此之后重命名列。

df <- data.frame(
  a = c(1:20),
  b = c(2:21),
  b2 = 3:22,
  b3 = 4:23,
  c = as.factor(c(rep(1, 5), rep(2, 10), rep(3, 5)))
)

library(tidyverse)
df %>%
  group_by(c) %>%
  mutate_at(vars(starts_with("b")), funs(lead = lead(.)))
#> # A tibble: 20 x 8
#> # Groups:   c [3]
#>        a     b    b2    b3 c     b_lead b2_lead b3_lead
#>    <int> <int> <int> <int> <fct>  <int>   <int>   <int>
#>  1     1     2     3     4 1          3       4       5
#>  2     2     3     4     5 1          4       5       6
#>  3     3     4     5     6 1          5       6       7
#>  4     4     5     6     7 1          6       7       8
#>  5     5     6     7     8 1         NA      NA      NA
#>  6     6     7     8     9 2          8       9      10
#>  7     7     8     9    10 2          9      10      11
#>  8     8     9    10    11 2         10      11      12
#>  9     9    10    11    12 2         11      12      13
#> 10    10    11    12    13 2         12      13      14
#> 11    11    12    13    14 2         13      14      15
#> 12    12    13    14    15 2         14      15      16
#> 13    13    14    15    16 2         15      16      17
#> 14    14    15    16    17 2         16      17      18
#> 15    15    16    17    18 2         NA      NA      NA
#> 16    16    17    18    19 3         18      19      20
#> 17    17    18    19    20 3         19      20      21
#> 18    18    19    20    21 3         20      21      22
#> 19    19    20    21    22 3         21      22      23
#> 20    20    21    22    23 3         NA      NA      NA

reprex包 (v0.2.0)創建於2018-09-07。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM