Bullmarket
Bullmarket

Reputation: 1

How to add for loop values into a vector

I have made following for loop and i got 10 values, but i need to transfer those values into a vector. How can i do it? I need to box plot those values.

oma <- function(y){ 
  x <- 6.1
  (x^y*exp(-x))/funktio(y)
}
oma(10)

y <- 1:10

for(i in y)
  print(oma(i))

Upvotes: 0

Views: 34

Answers (3)

akrun
akrun

Reputation: 887118

We can use lapply

vec <- unlist(lapply(y, oma))

Upvotes: 0

Gregor Thomas
Gregor Thomas

Reputation: 145775

You can do this

result = numeric(length = 10)
## only good if `y` is of the form `1:n`
for (i in y) {
  result[i] = oma(i)
}


## Safer version, works even if `y` doesn't start at 1 and increment by 1
result = numeric(length = length(y))
for (i in seq_along(y)) {
  result[i] = oma(y[i])
}

Everything you do in oma is vectorzied, so if funktio is also vectorized you could go directly to result = oma(y) without a loop.

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

You can use sapply :

vec <- sapply(y, oma)

Upvotes: 1

Related Questions