Function to calculate higher percentage of hires per region in R

Asked

Viewed 47 times

0

Hello,
I am trying to make a function that returns the highest percentage (Taxas_in) of hires in a region (Local), and the output would be the sector (Activity) and the respective rate with the highest percentage.
I can extract the highest percentage but I can’t extract the corresponding sector. Follows the code:

setor_maior_percentual_contratacoes_regiao <- function(df, regiao) {
  df_reg <- subset(df, Local == regiao)
  
  #calcula o vetor de setores da economia
  col_setores <- df_reg$Atividade
  setores <- col_setores[!duplicated(col_setores)]  # gera o vetor sem duplicação de valores

  #inicialmente considera o primeiro setor como o de maior percentual
  maior_taxa_in <- max(df_reg$Taxas_IN)
  setor_maior   <- setores[1]

  for(setor in setores){
    
    taxa_setor <- df_reg$Taxas_IN
    #verifica se o setor teve o maior percentual de contratações
    if(taxa_setor > maior_taxa_in){
      setor_maior <- df_reg$Atividade
      maior_taxa_in <- taxa_setor
    }
  }
  return(c(setor_maior, maior_taxa_in))
}

When I apply the function as in:

cat("\n Setor com maior número de contrataões na regiãoSul: 
     \n setor - percentual de contratações \n")
cat(result[1], " -- ", result[2])  

I have as a result 1 -- 7.7 but it should be B -- 7.7, where B is the sector corresponding to 7.7 (highest percentage for the South, in the case of the example)
What am I doing wrong?

  • Welcome to Stackoverflow! Unfortunately, this question cannot be reproduced by anyone trying to answer it. Please take a look at this link (mainly in the use of function dput) and see how to ask a reproducible question in R. So, people who wish to help you will be able to do this in the best possible way.

  • Can you please, edit the question with the departure of dput(df) or, if the base is too large, dput(head(df, 20))? (df is the basis that is passed to the function.)

No answers

Browser other questions tagged

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