r - How to use multiple arguments in mutate_all for any function? -


my data below

grp <- paste('group', sample(1:3, 100, replace = t)) x <- rnorm(100, 100) y <- rnorm(100, 10) df <- data.frame(grp = grp, x =x , y =y , stringsasfactors = f) lag_size <- c(10, 4, 9) 

now when try use

df %>% group_by(grp) %>% mutate_all(lag, n = lag_size) %>% arrange(grp) 

it gives error

error in mutate_impl(.data, dots) :  expecting single value: 

whereas works fine

df %>% group_by(grp) %>% mutate_all(lag, n = 10) %>% arrange(grp) 

if need lag based on 'grp' i.e. lag corresponding 'grp' value specified in 'lag_size'

library(tidyverse) res <- map2(split(df[2:3], df$grp) , lag_size, ~.x %>%                   mutate_all(lag, n = .y)) %>%                  bind_rows(., .id = 'grp') 

we can check lag in 'grp' position of first non-na element

res %>%        group_by(grp) %>%        summarise(n = which(!is.na(x))[1]-1) # tibble: 3 x 2 #     grp     n #    <chr> <dbl> #1 group 1    10 #2 group 2     4 #3 group 3     9 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -