Home > Net >  Create multiple columns with mutate (dplyr) in R using rollapplyr function
Create multiple columns with mutate (dplyr) in R using rollapplyr function

Time:01-26

I'm trying to create multiple columns using rollapplyr function with mutate() function.

Manually, i can do it:

df = data.frame(Vazao = seq(1,100))


df2 <- df %>%
  mutate(     
    roll1 = rollapplyr(Vazao, 1, mean, fill = NA, na.rm = T, partial = F),
    roll2 = rollapplyr(Vazao, 2, mean, fill = NA, na.rm = T, partial = F),
    roll3 = rollapplyr(Vazao, 3, mean, fill = NA, na.rm = T, partial = F),
    roll4 = rollapplyr(Vazao, 4, mean, fill = NA, na.rm = T, partial = F),
    roll5 = rollapplyr(Vazao, 5, mean, fill = NA, na.rm = T, partial = F),
    ); df2

But i think that's a smart way to create a lot of columns

I need to use dplyr because in future i'll use group_by() function

Thanks for help!

CodePudding user response:

We may use map

library(dplyr)
library(purrr)
library(zoo)
map_dfc(1:5,  ~ df %>% 
  transmute(roll = rollapply(Vazao, .x, FUN = mean,
   fill = NA, na.rm = T, partial = FALSE))) %>%
   bind_cols(df, .)

Or just use base R

df[paste0("roll", 1:5)] <- lapply(1:5, \(x) 
 rollapplyr(df$Vazao, x, FUN = mean, fill = NA, na.rm = TRUE, partial = FALSE))

-output

> head(df)
  Vazao roll1 roll2 roll3 roll4 roll5
1     1     1    NA    NA    NA    NA
2     2     2   1.5    NA    NA    NA
3     3     3   2.5     2    NA    NA
4     4     4   3.5     3   2.5    NA
5     5     5   4.5     4   3.5     3
6     6     6   5.5     5   4.5     4

CodePudding user response:

Another option would be to use purrr::reduce where I make use of some glue magic ("roll{.y}") to name the columns:

library(dplyr)
library(purrr)
library(zoo)

purrr::reduce(1:5, ~ mutate(
  .x,
  "roll{.y}" := rollapply(
    Vazao, .y, mean,
    fill = NA, na.rm = T, partial = F
  )
),
.init = df
)
#>     Vazao roll1 roll2 roll3 roll4 roll5
#> 1       1     1   1.5    NA    NA    NA
#> 2       2     2   2.5     2   2.5    NA
#> 3       3     3   3.5     3   3.5     3
#> 4       4     4   4.5     4   4.5     4
#> 5       5     5   5.5     5   5.5     5
#> 6       6     6   6.5     6   6.5     6
#> 7       7     7   7.5     7   7.5     7
#> 8       8     8   8.5     8   8.5     8
#> 9       9     9   9.5     9   9.5     9
#> 10     10    10  10.5    10  10.5    10
  •  Tags:  
  • r
  • Related