I need to solve a system of linear equations:
aQ + bP = c
dQ + eP = f
Where:
a ~ N(100;10)
b ~ N(-1;0.1)
c ~ N(10;1)
d ~ N(10;0
You could try using apply()
# data
df = data.frame(a,b,c,d,e,f)
# apply function
out = t(apply(df, 1,
function(x){
coefs = matrix( c(x['a'], x['d'], x['b'], x['e']), 2, 2);
ys = array(c(x['c'],x['f']),2);
out = solve(coefs, ys);
names(out) = c('P','Q');
out}))
Or else using sapply()
out = t(sapply(seq(100), function(i){
coefs = matrix(c(a[i], d[i], b[i] ,e[i]),2,2); ys = array(c(c[i],f[i]),2);
out = solve(coefs, ys); names(out) = c('P','Q');
out}))
and if you want to use for
loop, here is what you could do
# declare matrix to store the output
out = matrix(ncol=2, nrow=100)
# populate declared matrix using for loop
for(i in 1:100){
coefs = matrix(c(a[i],d[i],b[i],e[i]),2,2)
ys = array(c(c[i],f[i]),2)
out[i,] = as.vector(solve(coefs, ys))
colnames(out) = c('P','Q')
out}