123testerR
123testerR

Reputation: 21

Create multiple sequences with different lengths (length.out)

Let's say I have a vector,

n <- c(1:100)

and I want to output multiple sequences for each value 'n' takes in the vector above.

I tried doing something like this:

x <- seq (0,5, length.out = n+1)
x <- x[-1]

I get the error:

Warning Message: In seq.default(0,5, length.out = n+1) First element used of length.out argument

I then want to use 'x' for a calculating in:

fx <- dnorm(x, mean = 0 , sd = 4)

Where fx[1] will output the first value of fx and so on up to fx[n]

Upvotes: 2

Views: 283

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 102700

Maybe the following base R code can help

g <- Vectorize(function(k) seq (0,5, length.out = k+1)[-1])
x <- g(n)
fx <- sapply(x, dnorm, mean = 0,sd = 4)

such that

> head(x)
[[1]]
[1] 5

[[2]]
[1] 2.5 5.0

[[3]]
[1] 1.666667 3.333333 5.000000

[[4]]
[1] 1.25 2.50 3.75 5.00

[[5]]
[1] 1 2 3 4 5

[[6]]
[1] 0.8333333 1.6666667 2.5000000 3.3333333 4.1666667 5.0000000

and

> head(fx)
[[1]]
[1] 0.04566227

[[2]]
[1] 0.08204024 0.04566227

[[3]]
[1] 0.09144309 0.07047797 0.04566227

[[4]]
[1] 0.09498265 0.08204024 0.06426848 0.04566227

[[5]]
[1] 0.09666703 0.08801633 0.07528436 0.06049268 0.04566227

[[6]]
[1] 0.09759449 0.09144309 0.08204024 0.07047797 0.05797360 0.04566227

Upvotes: 1

see24
see24

Reputation: 1230

Is this what you wanted x to look like?

x <- lapply(n, function(i) seq (0,5, length.out = i+1))
x
[[1]]
[1] 0 5

[[2]]
[1] 0.0 2.5 5.0

[[3]]
[1] 0.000000 1.666667 3.333333 5.000000

[[4]]
[1] 0.00 1.25 2.50 3.75 5.00

[[5]]
[1] 0 1 2 3 4 5

[[6]]
[1] 0.0000000 0.8333333 1.6666667 2.5000000 3.3333333 4.1666667 5.0000000

Upvotes: 4

Related Questions