I have the following problem. I have a total of $N$ observations, and for each of these, I am evaluating absence (0) /presence (1) of a given factor. Let's call these factors $A$, $B$, $C$ and $D$.

I am only interested in the cases for which presence is evaluated for exactly two factors. Specifically, I am interested into testing whether a particular case, ${A=1, B=0, C=1, D=0}$ is statistically observed more or less than expected by chance, given the individual frequencies of the four factors in that set.

Let's consider the following example in R, where Nobs is the number of observations for each combination of factors, pairwise:

df <- data.frame(A = c(0,0,0,1,1,1),
                 B = c(0,1,1,0,0,1),
                 C = c(1,0,1,0,1,0),
                 D = c(1,1,0,1,0,0),
                 Nobs = c(613, 209, 298, 280, 382, 147))

Is Nobs = 382 different from the random expectation based on the frequency of occurrence of $A$ and $D$ separately?

I assume this can be done with chisq.test(x = c(613, 209, 298, 280, 382, 147), p = vector_of_expected_frequencies), and this should be a very easy task, but I am struggling getting the expected frequencies.

I would say that in my data set, $p(A)$, $p(B)$, $p(C)$ and $p(D)$ are the following:

pA <- dplyr::filter(df, A==1) %>% .$Nobs %>% sum() %>% `/`(2*N)
pB <- dplyr::filter(df, B==1) %>% .$Nobs %>% sum() %>% `/`(2*N)
pC <- dplyr::filter(df, C==1) %>% .$Nobs %>% sum() %>% `/`(2*N)
pD <- dplyr::filter(df, D==1) %>% .$Nobs %>% sum() %>% `/`(2*N)

Made this way, $p(A)+p(B)+p(C)+p(D)=1$ as expected, but then, the probability of all combinations pairwise will result in probabilities that do not sum to $1$, and are therefore not usable for the test. In fact, they add to a much lower number.

df %>%
  dplyr::mutate(tmpA = ifelse(A==0, 1, pA),
                tmpB = ifelse(B==0, 1, pB),
                tmpC = ifelse(C==0, 1, pC),
                tmpD = ifelse(D==0, 1, pD)) %>%
  dplyr::mutate(prod = tmpA*tmpB*tmpC*tmpD) %>%
  .$prod %>%

There must be something trivial I am missing here, any help is appreciated.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.