Loop through dataframe column names - R

70,375

To answer the exact question and fix the code given, see the example below

df <- iris # data

for (i in colnames(df)){
   print(class(df[[i]]))
}
# [1] "numeric"
# [1] "numeric"
# [1] "numeric"
# [1] "numeric"
# [1] "factor"
  1. you need to used colnames to get the column names of df.
  2. you access each column using df[[i]] if you want to know the class of that. df[i] is of class data.frame.
Share:
70,375

Related videos on Youtube

Chris
Author by

Chris

Updated on June 19, 2020

Comments

  • Chris
    Chris almost 4 years

    I'm trying to loop through the columns names of a dataframe, and evaluate which class is each column.

    for (i in columns(df)){
      class(df$i)
    }
    

    I have tried everything, except the right way..

    PS: I'm trying to do in this way because after I have to put different conditions for each class.

    • Sathish
      Sathish about 6 years
      sapply(df, class)
    • Jorge
      Jorge about 6 years
      for (i in 1:length(df)){ class(df[,i]) }
    • hpesoj626
      hpesoj626 about 6 years
      I don't know what operations you want to do later, but are you familiar with dplyr::mutate_if or dplyr::summarise_if sets of functions?
  • viridius
    viridius about 4 years
    Is it possible to begin looping on a different column (e.g., column 11) other than the first column?
  • Christopher Moore
    Christopher Moore almost 4 years
    Please provide some explanation to go with this code.