I have two sets of data stored in tables, one of them is a set [a, b], and the other is [x, Sx, y, Sy, rho]. I have a probability function ffor which it is required (a, b, x, Sx, y, Sy, rho). In the end, I want to find the sum of the probability results for all of the [x, Sx, y, Sy, rho]first [a, b]. Then find the amount for everyone [x, Sx, y, Sy, rho]in the second [a, b], etc.
I would like to have several hundred lines in a file [x, Sx, y, Sy, rho]and several hundred thousand lines in a file [a, b].
I am wondering if there is a way to do this without using two loops? I tried the following and it does not work the way I want, but I know that it will be too slow.
I don't know if this will help, but I added a function to the code. Sorry that the function itself is a mess and is not formatted properly.
data <- matrix( c(1, 0, 1, 1, 0.5, 0), nrow=3, ncol=2)
colnames(data) <- c("a", "b")
Ndat <- dim(data)
Ndata <- Ndat[1]
data2 <- matrix( c(1, 0.1, 1, 0.1, 0.002, 2, 0.1, 2, 0.1, 0.000001,
2, 0.1, 1, 0.1, 0.002), nrow=3, ncol=5)
colnames(data2) <- c("x", "Sx", "y", "Sy", "rho")
Ndat2 <- dim(data)
Ndata2 <- Ndat[1]
Prob <- function(a, b, Xi, sX, Yi, sY, rho) {sqrt(1 + a ^ 2) * (
exp(-((b + a * Xi - Yi) ^ 2 / (
2 * ((a ^ 2 * sX ^ 2) -
(2 * a * rho * sX * sY) + sY ^ 2)))) * sqrt((
1 - rho ^ 2) / (
a ^ 2 * sX ^ 2 - 2 * a * rho *sX *sY + sY ^ 2))/(
sqrt(2 * pi) * sqrt(1 - rho ^ 2)))
}
Table <- NULL
Table <- for (j in 1:Ndata) {
sum (for (i in 1:Ndata2) {
Datatable[i] = Prob(data[j, a], data[j, b], data2[i, x],
data2[i, Sx], data2[i, y], data2[i, Sy],
data2[i, rho])
})
}
It is very difficult for me to wrap my head around functions applyand when they can / should be used. I know that I probably did not add enough information, so any suggestions that might help me would be great. I am new to programming as well as to R, so please forgive any inappropriate dictionary or formatting.
There is probably a better way to determine the number or lines in datato get Ndataas global, but these are the first ones that I stumbled upon.
, , , . R, , apply.
, data2, a, b data. sum . 2 data, a, b, data2