I want to create a for loop which is able to handle multiple condition and keep result in a matrix named mat
. for this purpose, I have a data frame named df
and a sequence of numbers which I am used as weight
named w
.
w<- seq(.01,.1, .009)
mat<- matrix(0,11,10)
df<- data.frame(year=c( 2000:2010), ph= c(12:22), ph_fit=c(14,15,18,16,20,15,17,23,11,19,26)
,b= c(-2,-1,3,-1.5,-4,5,5.5,-6,3.5,2.1,-5.4))
what I want is simulating b
for each year based on value in w
using this conditions:
if ph_fit > ph, the new estimate of b (b_fit)
will be b_fit= b* 1 (w)
(where b <0 ) and b_fit=b* 1-w
(where b >0).
for next condition I have:
if ph_fit < ph, the new estimate of b (b_fit)
will be b_fit= b* 1 w
(where b > 0 ) and b_fit=b* 1-w
(where b < 0).
this is an iterative process and repeat for each value in w
.
by the code below, I have tried but got some error:
for (i in 1: 11) {
if (df$ph_fit > df$ph & df$b < 0) {
mat[, i] = df$b * 1 w
} else if (df$b > 0) {
mat[, i] = df$b * 1 - w
} else if (df$ph_fit < df$ph & df$b < 0) {
mat[, i] = df$b * 1 - w
} else if (df$b > 0) {
mat[, i] = df$b * 1 w
}
}
my expected output for b_fit
would be like this:
`2000` `2001` `2002` `2003` `2004` `2005` `2006` `2007` `2008` `2009` `2010`
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 w1 -2.02 -1.01 2.97 -1.52 -4.04 5.05 5.56 -6.06 3.46 2.12 -5.45
2 w2 -2.04 -1.02 2.94 -1.53 -4.08 5.10 5.60 -6.11 3.43 2.14 -5.50
3 w3 -2.06 -1.03 2.92 -1.54 -4.11 5.14 5.65 -6.17 3.40 2.16 -5.55
4 w4 -2.07 -1.04 2.89 -1.56 -4.15 5.18 5.70 -6.22 3.37 2.18 -5.60
5 w5 -2.09 -1.05 2.86 -1.57 -4.18 5.23 5.75 -6.28 3.34 2.20 -5.65
6 w6 -2.11 -1.06 2.84 -1.58 -4.22 5.28 5.80 -6.33 3.31 2.22 -5.70
7 w7 -2.13 -1.06 2.81 -1.60 -4.26 5.32 5.85 -6.38 3.28 2.23 -5.75
8 w8 -2.15 -1.07 2.78 -1.61 -4.29 5.36 5.90 -6.44 3.24 2.25 -5.79
9 w9 -2.16 -1.08 2.75 -1.62 -4.33 5.41 5.95 -6.49 3.21 2.27 -5.84
10 w10 -2.18 -1.09 2.73 -1.64 -4.36 5.46 6.00 -6.55 3.18 2.29 -5.89
11 w11 -2.2 -1.1 2.7 -1.65 -4.4 5.5 6.05 -6.6 3.15 2.31 -5.94
CodePudding user response:
I believe the main problem with your loop, is that you in each iteration use all "df", which mean that your "if" statements have multiple outputs. i.e. for the first "if" statement of the first iteration
"df$ph_fit > df$ph & df$b < 0" gives [1] TRUE TRUE FALSE TRUE TRUE FALSE FALSE TRUE FALSE FALSE TRUE
So you need to subset your data, inside the loop, example below below. In addition, be aware of the dimensions of your matrix which ends up 11x11 (not 11x10).
w<- seq(.01,.1, .009)
mat<- matrix(0,11,11)
df<- data.frame(year=c( 2000:2010), ph= c(12:22), ph_fit=c(14,15,18,16,20,15,17,23,11,19,26)
,b= c(-2,-1,3,-1.5,-4,5,5.5,-6,3.5,2.1,-5.4))
for (i in 1:11){
data <- df[i, ]
if(data$ph_fit > data$ph & data$b < 0)
{ mat[,i] = data$b * 1 w}
else if (data$b > 0 )
{mat[,i] = data$b * 1-w}
else if( data$ph_fit < data$ph & data$b < 0)
{mat[,i]= data$b * 1-w}
else if (data$b > 0)
{mat[,i] = data$b * 1 w}
}