1

I'm learning R and I'd like to make an "array of arrays" (not sure if the expression is correct) inserting for example these values

N_seq = c(10,50,100,500,1000)

inside this function (not correct):

x = rnorm(N_seq,3.2,1)

The desired result should be like an object made by five arrays (as length(N_seq) = 5) where each one is equal to the result of x inserting each value of N_seq (so that x[1] has the values of rnorm(N_seq[i], 3.2, 1) with length 10, and x[2] has the values rnorm(N_seq[2], 3.2, 1) with length 50, etc.

0

1 Answer 1

1

For ragged array, use "list". This is a special type of "vector" in R. You can not only hold vectors of difference length in each list element, but also different type of objects for each list element.

The lapply function for "list apply" is frequently used to process a list and / or return a list. For your task, you can do:

lapply(N_seq, FUN = rnorm, mean = 3.2, sd = 1)

lapply applies function FUN to each vector elements of N_seq, where mean = 3.2 and sd = 1 are additional parameters passed to FUN, which is rnorm here.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi, i tried for example to set a seed but i receive different results: set.seed(42) N_seq = c(10,50,100,500,1000) a=rnorm(10,3.2,1) b=lapply(N_seq, FUN = rnorm, mean = 3.2, sd = 1) print(a) print(b[1])
I knew setting a seed the numbers should be always the same
Great it works! I didn't know that, is there a way to set just one time the seed so that I don't initialize it every time?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.