How to retrieve the most repeated value in a column present in a data frame

前端 未结 6 2144
礼貌的吻别
礼貌的吻别 2020-12-16 00:08

I am trying to retrieve the most repeated value in a particular column present in a data frame.Here is my sample data and code below.A

data(\"Forbes2000\", p         


        
6条回答
  •  北海茫月
    2020-12-16 01:04

    I know my answer is coming a little late, but I built the following function that does the job in less than a second for my dataframe that contains more than 50,000 rows:

    print_count_of_unique_values <- function(df, column_name, remove_items_with_freq_equal_or_lower_than = 0, return_df = F, 
                                             sort_desc = T, return_most_frequent_value = F)
    {
      temp <- df[column_name]
      output <- as.data.frame(table(temp))
      names(output) <- c("Item","Frequency")
      output_df <- output[  output[[2]] > remove_items_with_freq_equal_or_lower_than,  ]
    
      if (sort_desc){
        output_df <- output_df[order(output_df[[2]], decreasing = T), ]
      }
    
      cat("\nThis is the (head) count of the unique values in dataframe column '", column_name,"':\n")
      print(head(output_df))
    
      if (return_df){
        return(output_df)
      }
    
      if (return_most_frequent_value){
          output_df$Item <- as.character(output_df$Item)
          output_df$Frequency <- as.numeric(output_df$Frequency)
          most_freq_item <- output_df[1, "Item"]
          cat("\nReturning most frequent item: ", most_freq_item)
          return(most_freq_item)
      }
    }
    

    so if you have a dataframe called "df" and a column called "name" and you want to know the most comment value in the "name" column, you could run:

    most_common_name <- print_count_of_unique_values(df=df, column_name = "name", return_most_frequent_value = T)    
    

提交回复
热议问题