Loop in R with indexing and array

2

We are trying to use the for command to run a function y (say y=5+3x+4z ) by varying the values of z (say that z is a combination of 5 z=c(1,2,3,4,5) ) and that x is a normal size distribution 1000. After printing the values we used by indexing, how could we transform these results into an array of 1000 rows and 5 columns (1000 observations for each z value)? After using the for command:

z=c(1,2,3,4,5)
for(i in c(1,2,3,4,5)) print(y<-5+3x+4z[i]))

We tried to define an array of y that does not work because it printed the first column on the remaining 4.

    
asked by anonymous 29.03.2014 / 22:06

3 answers

2

Difficult to understand the result expected by the OP, but here is an attempt.

Y = matrix(NA,nrow=0,ncol=5)
x=c(0,1,2,3,4) 
z=c(1,2,3,4,5) 
for (i in 1:5) {
  y = 1*x+2*z[i]
  Y = rbind(Y,y) 
}  
Y
  [,1] [,2] [,3] [,4] [,5]
y    2    3    4    5    6
y    4    5    6    7    8
y    6    7    8    9   10
y    8    9   10   11   12
y   10   11   12   13   14
    
30.03.2014 / 03:14
1

Assuming a normal distribution of mean 0 and standard deviation 1:

x <- rnorm(1000, mean = 0, sd = 1)
z <- c(1, 2, 3, 4, 5)
Y <- matrix(NA, 1000, 0)

for (i in z) {
  y <- 5 + 3*x + 4*i
  Y <- cbind(Y,y)
}

print(tail(Y))

                y         y        y        y        y
[995,]   4.450844  8.450844 12.45084 16.45084 20.45084
[996,]   9.072672 13.072672 17.07267 21.07267 25.07267
[997,]   8.609610 12.609610 16.60961 20.60961 24.60961
[998,]   6.977799 10.977799 14.97780 18.97780 22.97780
[999,]   5.896328  9.896328 13.89633 17.89633 21.89633
[1000,] 13.005769 17.005769 21.00577 25.00577 29.00577

At the end, Y will have 1000 rows and 5 columns. That is, 1000 observations for each value of z.

    
30.03.2014 / 17:09
1

You do not need to use for in this case.

A solution with sapply follows:

y <- function(x,z) 5+3*x+4*z
set.seed(1)
x <- rnorm(1000, mean = 0, sd = 1)
z <- c(1, 2, 3, 4, 5)
resultados<-sapply(z, y, x=x)

The results will be 5 columns (one for each z) with 1000 observations:

head(resultados) ### mostrando apenas os 6 primeiros
      [,1]     [,2]     [,3]     [,4]     [,5]
[1,]  7.120639 11.12064 15.12064 19.12064 23.12064
[2,]  9.550930 13.55093 17.55093 21.55093 25.55093
[3,]  6.493114 10.49311 14.49311 18.49311 22.49311
[4,] 13.785842 17.78584 21.78584 25.78584 29.78584
[5,]  9.988523 13.98852 17.98852 21.98852 25.98852
[6,]  6.538595 10.53859 14.53859 18.53859 22.53859
    
30.03.2014 / 17:59