Search code examples
rclassificationnames

Return column numbers that are classified as logical


I am trying to write a function that will run only on the logical columns in my dataframe. To do this I am first trying to generate a list of the column numbers in my data frame which are classified as "logical."

For dataframe m here are how my data is classified:

str(m)
'data.frame':   169 obs. of  42 variables:
 $ Municipality                  : chr  "Andover" "Ansonia" "Ashford" "Avon" ...
 $ Webpage_Link                  : chr  "http://andoverconnecticut.org/services-government/building-zoning/" "http://www.cityofansonia.com/content/2524/2582/default.aspx" "http://www.ashfordtownhall.org/government/land-use/building-department/" "http://www.avonct.gov/building-department" ...
 $ Webpage_LastUpdate            : chr  NA NA NA NA ...
 $ Researcher                    : chr  "DM" "DM" "LG" "LG" ...
 $ Collection.Date               : chr  "11/4/15" "11/4/15" "1/26/16" "1/26/16" ...
 $ Complete                      : logi  TRUE TRUE TRUE TRUE TRUE TRUE ...
 $ Application_BuildPermit       : logi  TRUE FALSE TRUE TRUE FALSE TRUE ...
 $ Application_SolarPermt        : logi  FALSE FALSE TRUE TRUE FALSE FALSE ...
 $ Contact_Name                  : logi  TRUE TRUE TRUE TRUE TRUE FALSE ...
 $ Contact_Address               : logi  TRUE TRUE TRUE TRUE TRUE TRUE ...

Solution

  • (df <- data.frame(a = 1:3, b = letters[1:3], c = TRUE))
    #   a b    c
    # 1 1 a TRUE
    # 2 2 b TRUE
    # 3 3 c TRUE
    
    sapply(df, is.logical)
    #     a     b     c 
    # FALSE FALSE  TRUE
    

    If you really need a vector of numbers then you may additionally apply which:

    which(sapply(df, is.logical))
    # c 
    # 3