Import your data

data <- read_xlsx("myData.xlsx")

Create Data frame functions

Example 1: count columns

code snippets

ncol_num <- data %>%
  select(where(is.numeric)) %>%
  ncol()
ncol_num
## [1] 2

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 variable
  return(ncol_num)
  
}

data %>% count_ncol_numeric()
## [1] 2

Adding arguments for details of operation

count_ncol_type <- function(.data, type_data = "numeric") {
  
  if(type_data == "numeric") {
    ncol_type <- .data %>%
      select(where(is.numeric)) %>%
      ncol()
  } else if(type_data == "character") {
    ncol_type <- .data %>%
      select(where(is.character)) %>%
      ncol()
  }
  
  # return the new variable
  return(ncol_type)
  
}

data %>% count_ncol_type()
## [1] 2
data %>% count_ncol_type(type_data = "character")
## [1] 13

Example 2: count rows

code snippets

nrow_num <- data %>%
  filter(season == "Summer") %>%
  nrow()
nrow_num
## [1] 222552

Turn them into a function

count_num_by_season <- function(.data, season_name) {
  
  # body
  nrow_num <- .data %>%
    
    # filter rows that meet a condition
    filter(season == season_name) %>%
    
    # Count rows
    nrow()
  
  # return the new variable
  return(nrow_num)
  
}

data %>% count_num_by_season(season_name = "Summer")
## [1] 222552
data %>% count_num_by_season(season_name = "Winter")
## [1] 48564

Example 3: count rows

code snippets

nrow_medal <- data %>%
  filter(medal == "Gold") %>%
  nrow()
nrow_medal
## [1] 13372

Turn them into a function

count_num_by_medal <- function(.data, medal_name) {
  
  # body
  nrow_medal <- .data %>%
    
    # filter rows that meet a condition
    filter(medal == medal_name) %>%
    
    # Count rows
    nrow()
  
  # return the new variable
  return(nrow_medal)
  
}

data %>% count_num_by_medal(medal_name = "Gold")
## [1] 13372
data %>% count_num_by_medal(medal_name = "Silver")
## [1] 13116