Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are several ways to detect and count common elements in R, depending on the data structure that contains the elements. Here are a few examples:

  1. Vectors: To count common elements in two vectors, you can use the intersect() function, which returns the elements that are common to both vectors. Then, you can use the length() function to count the number of common elements.
vec1 <- c(1, 2, 3, 4)
vec2 <- c(3, 4, 5, 6)
common <- intersect(vec1, vec2)
count <- length(common)
  1. Lists: To count common elements in two lists, you can use a similar approach as for vectors, but you need to apply it to each element of the lists. One way to do this is to use the lapply() function to apply the intersect() function to each pair of elements, and then use the sapply() function to count the number of common elements in each pair.
list1 <- list(a = c(1, 2, 3), b = c(3, 4, 5))
list2 <- list(a = c(3, 4, 5), b = c(5, 6, 7))
common <- lapply(seq_along(list1), function(i) intersect(list1[[i]], list2[[i]]))
count <- sapply(common, length)
  1. Data frames: To count common elements in two columns of a data frame, you can use the merge() function to create a new data frame that contains only the common elements. Then, you can use the nrow() function to count the number of rows in the new data frame.
df <- data.frame(x = c(1, 2, 3, 4), y = c(3, 4, 5, 6))
common <- merge(df[df$x %in% df$y, "x"], df[df$y %in% df$x, "y"])
count <- nrow(common)