1

Hello I really need help with my program in R. I have vector with nine elements and I need divide each element by first, second, ...., hundredth, element from another vector. I try this for loop but it didn't works

er=matrix(1,100)
LCZ2016=matrix(1,100)

for(i in 2:100)
  for(j in 1:9)
  {
    {
      er[i]=rnorm(1, 0, SdeLcCZ2016)
      LCZ2016[i]=DEA['L'][CZ2016,][j,]/exp(er[i])
    } 
  }

the =DEA['L'][CZ2016,] is vector with 9 elements and I need create LCZ2016 with 100 elements like this

LCZ2016[1]=DEA['L'][CZ2016,][1] //exp(er[1])
LCZ2016[2]=DEA['L'][CZ2016,][2] //exp(er[2])
.
.
.
LCZ2016[50]=DEA['L'][CZ2016,][1] //exp(er[50])

etc. Please do you have any idea ?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • 1
    This should be possible. But please provide a _minimal_ [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – markus Dec 09 '18 at 11:45

2 Answers2

1

I think you can do:

a <- 1:9
b <- 1:100 

output = sapply(a, function(x) x/b)
print(dim(output))

[1] 100   9

Also, you can do as suggested by @Andre

sapply(a, /, b)
YOLO
  • 20,181
  • 5
  • 20
  • 40
1

This is exactly what outer is meant for.

a <- 1:9
b <- 1:100 
out2 <- outer(a, b, '/')
dim(out2)
#[1]   9 100

Compare with YOLO's answer.

output <- sapply(a, function(x) x/b)

identical(t(out2), output)
#[1] TRUE
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66