I have a dataframe that looks like this:
x <- c(1,2,1,1,4,NA,NA,NA,NA,NA)
y <- c(21,22,23,21,21,NA,NA,NA,NA,NA)
z <- c(NA,NA,NA,NA,NA,1,2,3,4,5)
dat <- data.frame(x,y,z)
I want to count how many times a value from x occurs in z and then take the value of y that corresponds to that row of x. I'm assuming I'll need to use a for loop or apply. The counts would populate a data frame or matrix with column headings corresponding to the y values. I've looked through Stack Overflow and I've tried using which and %in% with no luck. I've also tried sum but it only looks across a row and sums matching occurrences. I want to look across all rows of the other column of interest (z).
The result would look like this (z as the row labels, y as column labels):
21 22 23
1 2 0 1
2 0 1 0
3 0 0 0
4 1 0 0
5 0 0 0