The “lead” Function in R

  • Package: dplyr

  • Purpose: To shift or lead values in a vector or data frame column.

  • General Class: Data Manipulation

  • Required Argument(s):

    • x: A vector or column of a data frame that you want to lead.

  • Notable Optional Arguments:

    • n: An integer specifying the number of positions to shift the values. The default is 1.

    • default: The value to use for the lead of the last element or the lag of the first element. The default is NA.

  • Example:

  • # Example usage
    library(dplyr)

    my_vector <- c(1, 2, 3, 4, 5)

    # Lead the values by 1 position
    lead_values <- lead(my_vector, n = 1)

    print(lead_values)

  • In this example, lead is a function from the dplyr package, and it is used to shift or lead values in a vector. The x argument is the required vector or column of a data frame that you want to lead. The n argument is optional and specifies the number of positions to shift the values (default is 1). The default argument is also optional and sets the value to use for the lead of the last element or the lag of the first element (default is NA). The result is a vector with lead values.

Previous
Previous

The “log” Function in R

Next
Next

The “lag” Function in R