1

Here is my data:

ID <- c(1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 1)
group <- c(11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 14)
x1 <- c(0.1, 0.2, 0.3, 1.1, 1.2, 1.3, 1.4, 2.1, 2.2, 2.3, 3.1)
x2 <- c(0.4, 0.5, 0.6, 1.4, 1.5, 1.6, 1.7, 2.4, 2.5, 2.6, 3.4)
x3 <- c(0.7, 0.8, 0.9, 1.7, 1.8, 1.9, 1.0, 2.7, 2.8, 2.9, 3.9)
z1 <- c(0.4, 0.5, 0.6, 1.4, 1.5, 1.6, 1.7, 2.4, 2.5, 2.6, 3.4)
z2 <- c(0.7, 0.8, 0.9, 1.7, 1.8, 1.9, 1.0, 2.7, 2.8, 2.9, 3.7)
x <- as.matrix(data.frame(ID, group, x1, x2, x3))
z <- as.matrix(data.frame(ID, group, z1, z2))

For group 14, there is only one observation. I want to calculate x'z by group using

data1 <- lapply(unique(x[,'group']), function(i) 
crossprod(x[x[, 2] == i, c(-1, -2)], z[z[, 2] == i, c(-1, -2)]))

But it gives me the error Error in crossprod(x[x[, 2] == i, c(-1, -2)], z[z[, 2] == i, c(-1, -2)]) : non-conformable arguments.

I try i = 14 explicitly, and I am sure this is where the problem happens. I don't understand, if I calculate x'x or z'z, there will not be any problem. Any suggestions?

DXC
  • 75
  • 1
  • 7
  • It will not be easy to help you without a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Try creating a table with fake data to see if you can replicate the problem. – MrFlick Aug 21 '17 at 20:39
  • @MrFlick Very hard. I try to test using a subset which is feasible to be presented here, but I cannot replicate the problem. Any suggestions or guesses will be appreciated. – DXC Aug 21 '17 at 20:51
  • 1
    @MrFlick I think I find the problem. I use `t(X) %*% Z` instead of `crossprod`, this time the error report gives me which `i` causes the error. It turns out for groups with one count the matrix multiplication will fail. Is there a way to fix it except deleting this kind of groups? – DXC Aug 21 '17 at 21:10

0 Answers0