Last active
July 19, 2019 17:01
-
-
Save joaopcnogueira/e937e07fd001a7b53f64b2a98f459c7a to your computer and use it in GitHub Desktop.
Custom group_by function in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(tidyverse) | |
# toy dataset | |
df <- tibble( | |
clientes = c('joao', 'joao', 'joao', 'lucas', 'lucas', 'julia', 'julia', 'julia', 'julia'), | |
produtos = c('celular', 'notebook', 'livro', 'bola', 'carro', 'chapéu', 'moto', 'moto', 'caneta') | |
) | |
# função customizada | |
get_produtos <- function(produtos){ | |
lista_produtos <- tolower(paste(unique(produtos), collapse = ';')) | |
return(lista_produtos) | |
} | |
# criando a tabela lookup | |
lookup <- df %>% | |
group_by(clientes) %>% | |
summarise_at(vars(produtos), get_produtos) | |
# OUTPUT | |
# A tibble: 3 x 2 | |
# clientes produtos | |
# <chr> <chr> | |
# 1 joao celular;notebook;livro | |
# 2 julia chapéu;moto;caneta | |
# 3 lucas bola;carro | |
# juntando as tabelas | |
df <- left_join(df, lookup, by = c("clientes" = "clientes")) | |
# OUTPUT | |
# A tibble: 9 x 3 | |
# Groups: clientes [3] | |
# clientes produtos lista_produtos | |
# <chr> <chr> <chr> | |
#1 joao celular celular;notebook;livro | |
#2 joao notebook celular;notebook;livro | |
#3 joao livro celular;notebook;livro | |
#4 lucas bola bola;carro | |
#5 lucas carro bola;carro | |
#6 julia chapéu chapéu;moto;caneta | |
#7 julia moto chapéu;moto;caneta | |
#8 julia moto chapéu;moto;caneta | |
#9 julia caneta chapéu;moto;caneta | |
# Forma mais direta de criar a tabela final | |
df <- tibble( | |
clientes = c('joao', 'joao', 'joao', 'lucas', 'lucas', 'julia', 'julia', 'julia', 'julia'), | |
produtos = c('celular', 'notebook', 'livro', 'bola', 'carro', 'chapéu', 'moto', 'moto', 'caneta') | |
) | |
df %>% | |
group_by(clientes) %>% | |
mutate(lista_produtos = get_produtos(produtos)) | |
# OUTPUT | |
# A tibble: 9 x 3 | |
# Groups: clientes [3] | |
# clientes produtos lista_produtos | |
# <chr> <chr> <chr> | |
#1 joao celular celular;notebook;livro | |
#2 joao notebook celular;notebook;livro | |
#3 joao livro celular;notebook;livro | |
#4 lucas bola bola;carro | |
#5 lucas carro bola;carro | |
#6 julia chapéu chapéu;moto;caneta | |
#7 julia moto chapéu;moto;caneta | |
#8 julia moto chapéu;moto;caneta | |
#9 julia caneta chapéu;moto;caneta |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment