Loop in R with indexing and matrix

Asked

Viewed 830 times

2

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

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 a y matrix that does not work because it printed the first column in the other 4 remaining.

  • post the code you are using, and the expected result so we can help.

  • z=c(1,2,3,4,5)&#xA;y<-5+3x+4z&#xA;for(i in c(1,2,3,4,5)) print(matrix(5+3x+4z[i],100,5))

  • x=c(1,2,3,4,5) z=c(1,2,3,4,5) for(i in 1:5) print(Matrix(5+3x+4z[i],100,5)) the expected result has to be a five-column matrix (each column for the 5 z’s) and 5 rows (each row for the 5 x’s).

3 answers

2

Hard to understand what the result expected by the OP, but here goes a try.

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

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.

1

You don’t need to use for in this case.

Follows a solution with sapply:

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)

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.