Bắt đầu ngayBắt đầu miễn phí

Function returns and exporting

When documenting the return value of a function, you specify what users can expect as the output of the function, whether it's data, a number, a vector of strings, or any other R result.

While the NAMESPACE file is responsible for identifying exported functions, you create this file using roxygen2 tags. By using these tags, you can easily determine whether users will have access to a function right alongside its documentation. You mark a function for exporting in the roxygen2 header. This straightforward approach ensures that you can clearly indicate which functions are available for users to work with in the documentation itself.

Bài tập này là một phần của khóa học

Developing R Packages

Xem khóa học

Hướng dẫn bài tập

  • Document the return value with the following description: "A numeric distance value in the unit specified as `unit_to`."
  • Export the function.

Bài tập tương tác thực hành trực tiếp

Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.

#' Convert between distances
#'
#' Performs the conversion based on specified `unit_from` and `unit_to` values.
#'
#' @param dist_value A numerical distance value to be converted.
#' @param unit_from A character string of the distance unit to convert from 
#' @param unit_to A character string of the distance unit to convert to
# Add returning value description and tag
___
# Export this function
___
dist_converter <- function(dist_value, unit_from, unit_to) {
  if (unit_from == "feet" && unit_to == "meters") {
    return(dist_value / 3.28)
  } else if (unit_from == "meters" && unit_to == "feet") {
    return(dist_value * 3.28)
  } else if (unit_from == unit_to) {
    warning("unit_from and unit_to are the same, returning dist_value")
    return(dist_value)
  } else {
    stop("This function only supports conversions between feet and meters.")
  }
}
Chỉnh sửa và Chạy Mã