Import your data

data <- read_excel("../00_data/myData.xlsx")

Create Data frame functions

Example 1: count columns

code snippets

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

ncol_num
## [1] 9

Turn them into a function

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

data %>% count_ncol_numeric()
## [1] 9
data %>% .[1:10, 1:5] %>% count_ncol_numeric()
## [1] 1

Adding arguments for details of operation

count_ncol_type <- function(.data, type_data = "numeric") {
    
   # if statement for type of variables
    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 variables
    return(ncol_type)
}

data %>% count_ncol_type()
## [1] 9
data %>% count_ncol_type(type_data = "character")
## [1] 13
data %>% .[1:10, 1:5] %>% count_ncol_type(type_data = "character")
## [1] 4

Example 2: count rows

code snippets

nrow_num <- data %>%
    
    # filter rows that meet a condition
    filter(type == "Studio") %>%
    
    # Count rows
    nrow()

nrow_num
## [1] 608

Turn them into a function

count_num_albums_by_type <- function(.data, type_name) {
    
    # body
    nrow_num <- data %>%
        
        # filter rows that meet a condition
        filter(type == "Studio") %>%
        
        # count rows
        nrow()
    
    # return to new variable
    return(nrow_num)
}

data %>% .[1:10, "type"] %>%
    count_num_albums_by_type(type_name = "Studio")
## [1] 608