Q:

How to compare two columns of one data.frame with one specific column of another data.frame in R?

Background:
I have two data.frames, one with multiple Companies and another with one Index, 
I am trying to count when these two conditions are met:
1st condition: two companies move along (only when A=A or C=C) 
2nd condition: index shows opposite direction, when companies show A=A, index shows C or when companies show C=C, index shows A
Example: 1st column - Comp1 (C) Comp3 (C) & 1st column - index1 (A) | COUNT = 1 
The 6 pairs would be Comp1 & Comp2, Comp1 & Comp3, Comp1 & Comp4, Comp2& Comp3, Comp2 & Comp4 and Comp3 & Comp4 - Plus the index for each of the pairs
Have no clue which function could help me with this...
Code for data.frames:
  #Data.frame1 COMPANIES

  comp1 <- c("C","A","B","B","A")
  comp2 <- c("A","A","C","C","C")
  comp3 <- c("C","B","B","A","A")
  comp4 <- c("C","C","A","A","A")

  dfcomp <- data.frame(comp1, comp2, comp3, comp4)

  #Data.frame2 INDEX

   index1 <- c("A","B","C","C","C")

   dfindex <- data.frame(index1)

Final output: like 4x4 matrix results in one row (just the interesting values) 
         [12i] [13i] [14i] [23i] [24i] [34i]
     [1]   0     2     2     0     0     3 

A:

One of the approach could be
library(dplyr)

comp_func <- function(x, y, temp, index){
  temp <- bind_cols(temp[,!is.na(match(names(temp), c(x, y)))], index)
  temp[,] <- lapply(temp, function(i) as.character(i))
  ret <- sum(temp[,1] == temp[,2] & 
             temp[,1] %in% c('A', 'C') &
             ((temp[,1]=='A' & temp[,3]=='C') | (temp[,1]=='C' & temp[,3]=='A')))
  return(ret)
}

df <- as.data.frame.matrix(t(combn(names(dfcomp),2)), stringsAsFactors = F)
df %>%
  rowwise() %>%
  mutate(val = comp_func(V1, V2, dfcomp, dfindex))

Output is:
  V1    V2      val
1 comp1 comp2     0
2 comp1 comp3     2
3 comp1 comp4     2
4 comp2 comp3     0
5 comp2 comp4     0
6 comp3 comp4     3

Sample data:
dfcomp <- structure(list(comp1 = structure(c(3L, 1L, 2L, 2L, 1L), .Label = c("A", 
"B", "C"), class = "factor"), comp2 = structure(c(1L, 1L, 2L, 
2L, 2L), .Label = c("A", "C"), class = "factor"), comp3 = structure(c(3L, 
2L, 2L, 1L, 1L), .Label = c("A", "B", "C"), class = "factor"), comp4 = structure(c(2L, 2L, 1L, 1L, 1L), .Label = c("A", "C"), class = "factor")), .Names = c("comp1", "comp2", "comp3", 
"comp4"), row.names = c(NA, -5L), class = "data.frame")

dfindex <- structure(list(index1 = structure(c(1L, 2L, 3L, 3L, 3L), .Label = c("A", 
"B", "C"), class = "factor")), .Names = "index1", row.names = c(NA, 
-5L), class = "data.frame")

