Import your data

Create Data frame functions

Example 1: count columns

code snippets

ncol_num <- flights %>%
    
    # Select a type of variables
    select(where(is.numeric)) %>%
    
    # Count columns
    ncol()

ncol_num
## [1] 14

Turn them into a function

count_ncol_numeric <- function(.data) {
    
       # body    
       nrow_num <- .data %>%
        
        # Select a type of variables
        select(where(is.numeric)) %>%
        
        # Count columns
        nrow() 
    
       # return the new variable
       return(ncol_num)
}

flights %>% count_ncol_numeric()
## [1] 14
flights %>% .[1:10, -1:-13] %>% count_ncol_numeric()
## [1] 14

Adding arguments for details of operation

count_ncol_type <- function(.data, type_data = "numeric") {
    
    # if statement for type of variable
    if(type_data == "numeric") {
         # body    
           ncol_type <- .data %>%
            
            # Select a type of variables
            select(where(is.numeric)) %>%
            
            # Count columns
            ncol()
    } else if(type_data == "character"){
         # body    
           ncol_type <- .data %>%
            
            # Select a type of variables
            select(where(is.character)) %>%
            
            # Count columns
            ncol()
    }
    
    
    
       # return the new variable
       return(ncol_type)
}
flights %>% count_ncol_type()
## [1] 14
flights %>% count_ncol_type(type_data = "character")
## [1] 4
flights %>% . [1:10, 1:5] %>% count_ncol_type(type_data = "character")
## [1] 0

Example 2: count rows

code snippets

nrow_num <- flights %>%
    
    # filter rows that meet a condition
    filter(carrier == "DL") %>%
    
    # Count rows
    nrow()

nrow_num
## [1] 48110

Turn them into a function

count_num_flights_by_carrier <- function(.data, carrier_name) {
    
        # body
        nrow_num <- .data %>%
        
        # filter rows that meet a condition
        filter(carrier == carrier_name) %>%
        
        # Count rows
        nrow()
    
    # return the new variable
    return(nrow_num)
    
}
flights %>% .[1:10, "carrier"] %>% count_num_flights_by_carrier(carrier_name = "AA")
## [1] 2

Example 3: count rows

Create your own.

code snippets

Use the filter() function to select rows that meet a condition. Refer to Chapter 5.2 Filter rows with filter()

count_num_flights_origin <- flights %>%
    
    filter(origin == "EWR") %>%
    
    nrow()

count_num_flights_origin
## [1] 120835

Turn them into a function

count_num_flights_origin <- function(.data, airport) {
    
    # body
    nrow_num <- .data %>%
        
        # filter rows that meet a condition
        filter(origin == airport) %>%
        
        # Count rows
        nrow()
    
    # return new variable
    return(nrow_num)
    
}

flights %>% count_num_flights_origin(airport = "EWR")
## [1] 120835