The “anyDuplicated” Function in R

  • Package: Base R (No specific package, it’s a built-in function)

  • Purpose: To find the index of the first duplicated element in a vector, data frame, or other structures.

  • General Class: Data Manipulation

  • Required Argument(s):

    • x: The input vector, data frame, or other structure to check for duplicated elements.

  • Notable Optional Arguments:

    • fromLast: A logical value indicating whether to consider duplicates from the last occurrence to the first. The default is FALSE.

  • Example:

  • # Example usage with a vector
    my_vector <- c(1, 2, 3, 1, 2, 4, 5)
    first_duplicated_index <- anyDuplicated(my_vector)

    print(first_duplicated_index)

    # Example usage with a data frame
    my_data_frame <- data.frame(
    Name = c("John", "Jane", "Bob", "John", "Alice"),
    Age = c(25, 30, 22, 25, 28)
    )

    first_duplicated_row_index <- anyDuplicated(my_data_frame)

    print(first_duplicated_row_index)

  • In this example, anyDuplicated is a built-in function in base R, and it can be used to find the index of the first duplicated element in vectors or rows in a data frame. The fromLast argument is optional and allows you to control whether duplicates from the last occurrence should be considered. The result is an integer indicating the index of the first duplicated element or row.

Previous
Previous

The “cumsum” Function in R

Next
Next

The “duplicated” Function in R