Transform the database into R - A kind of dynamic table

Asked

Viewed 840 times

0

I have a database as follows:

CNPJ    SIGLA      chave            CENTRAL
3333    CREDSUL    CACHOEIRODIM-ES  CECOOPES
4444    COOPSEFES  VITORIA-ES       CECOOPES
55555   CREDI      VITORIA-ES       CECOOPES
66666   CREDEXTRA  SERRA-ES         CECOOPES
99999   ACENTRA    CRICIUMA-SC      CECRED
77777   ACREDICOOP JOINVILLE-SC     CECRED
11111   CREDCREA   FLORIANOPOLIS-SC CECRED
22222   CATARINA   FLORIANOPOLIS-SC CECRED
1010101 CREDELESC  FLORIANOPOLIS-SC CECRED
88888   CREDIFIESC FLORIANOPOLIS-SC CECRED

I would like to have a final table as follows:

chave            CNPJ1  SIGLA1    CENTRAL1  CNPJ2   SIGLA2  CENTRAL2    CNPJ3   SIGLA3  CENTRAL3    CNPJ4   SIGLA4  CENTRAL4
CACHOEIRODIM-ES  3333   CREDSUL   CECOOPES                                  
VITORIA-ES       4444   COOPSEFES CECOOPES  55555   CREDI-ALIMENTO  CECOOPES                        
SERRA-ES         66666  CREDEXTRA CECOOPES                                  
CRICIUMA-SC      99999  ACENTRA   CECRED                                    
JOINVILLE-SC     77777  ACREDICOOP CECRED                                   
FLORIANOPOLIS-SC 11111  CREDCREA  CECRED    22222   CATARINA CECRED 1010101 CREDELESC   CECRED   88888  CREDIFIESC CECRED

I tried it with reshape but I didn’t quite get what I wanted. It is possible to do this directly with some package in R?

1 answer

1

I was able to do this in two stages. First used the dplyr to create "Siglan" and "Centraln":

##Criando o contador
relcoop <- relcoop[order(relcoop$chave),] 
relcoopw<-relcoop %>% 
  group_by(chave) %>% 
  mutate(countercentral=paste0("CENTRAL",row_number()))

relcoopw<-relcoopw %>% 
  group_by(chave) %>% 
  mutate(countersigla=paste0("SIGLA",row_number()))

Then transpus using the function spread package tidyr

##Tabela dinamica relcoop
library(tidyr)
relcoopwcentral<-spread(relcoopw,countercentral,CENTRAL)
relcoopwsigla<-spread(relcoopw,countersigla,SIGLA)
relcoopw<-cbind(relcoopwcentral,relcoopwsigla)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.