I have a data frame with more than 300 columns that are categorical but are encoded as numeric. Each of these columns has its own "type", that is, it has its own coding table. My problem is to create a new data frame with decoded variables.
I have loaded the following data frames:
- The main data frame called "data", which has 347 columns that I want to decode.
- an auxiliary data frame named "data_vars" with: name (variable.name) and "type" (data.type) of all main df variables
- an auxiliary data frame called "codes": with "type" (data.type), possible codes for the respective "type" and the meaning of each code
I'm trying to use dplyr to try to make it easier. What I've been able to do so far is:
# pego uma das variáveis do df principal
variavel <- "abc"
# busco no df "dados_vars" qual é o tipo desta variável
tipo.variavel <- as.character(dados_vars[dados_vars$variable.name == variavel, "data.type"])
# filtro no df "codes" os códigos específicos que esta variável pode ter
codigos <- codes %>% filter(data.type==tipo.variável) %>% select(value,content)
# crio um novo data frame com esta variável decodificada
novos.dados <- mutate(dados, var1=factor(var1,label=codigos$content,levels=codigos$value))
Now, how do I apply this procedure to all columns in the main df?