Selecting and arranging column data in R

Viewed 44

I have this data set that requires some cleaning up. Is there a way to code in R such that it picks up columns with more than 3 different levels from the data set? Eg column C has the different education level and I would like it to be selected along with column D and F. While column E and G wont be picked up because it doesnt meet the more than 3 level requirement.

At the same time I need one of the columns to be arranged in a specific way? Eg Education, I would like PHD to be at the top. The other levels of education does not need to be in any order

Sorry i am really new to R and I attached a snapshot of a sample data i replicated from the original All help is greatly appreciated

1 Answers

It is a bit complicated to replicate the data as it is an image, but you could use this function to select those columns of your dataframe that have at least 3 levels.

First I converted to factor those columns you are considering, in this case from column C or 3. Then with the for loop I identify those columns with more than 2 levels, and save the result in a vector and then filter the original data set according to these columns.

select_columns <- function(df){
  
  df <- data.frame(lapply(df[,-c(1,2)], as.factor))
  selectColumns <- c()
  
  for (i in 1:length(df)) {
    if((length(unique(df[,i])) > 3) ){
      selectColumns[i] <- colnames(df[i])
    }
  }
  selectColumns <- na.omit(selectColumns)
  
  return(data %>% select(c(1:2),selectColumns))
    
}

select_columns(your_data_frame)
Related