0

I have a code,and i am going to do a for loop on two gamma distributions.

Given the list of shape parameter, and i name them "d" then i put in d[1] and d[2] in the random gamma function.

I have simplified what I wish to ask here. when i code d[1] in R, output will be the first vector,while when i code d[2] in R, output will be the second vector. I have a bit lose then how will it iterate if i using for loop for d ?

*
List_1  <- list(c(4,16),c(16/9,4),c(1,16/9),c(.64,1),c(4/9,.64))
for ( d in List_1)  ##first parameter is for gamma.1, second is for gamma.2
{
 x<-rgamma(25,d[1],1)
 y<-rgamma(25,d[2],1)

 t<-t.test(x,y)$p.value
}*

I am sorry if i do ask a silly question. Thanks in advance.

Cœur
  • 37,241
  • 25
  • 195
  • 267
j.l
  • 25
  • 8
  • What are x and y in your example? Where is d used in the for loop? – user1357015 Apr 13 '16 at 01:46
  • I am confused about your question. More precisely: what are you actually asking? Does your code produce the desired output? If yes, you can keep it as it is. The difference in performance between a `for` loop and `*apply` functions is [negligible or non-existing](http://stackoverflow.com/a/2276001/4770166). – RHertel Apr 13 '16 at 02:31
  • Are you receiving any error in above code? – Kunal Puri Apr 13 '16 at 02:37
  • @user1357015 x and y are samples took from distribution randomly. for the use of "d" in for loop, i have edited my question. you may take a look. But i am still new in R , so please forgive me if i have any mistake in interpreting ...> – j.l Apr 13 '16 at 04:26
  • @RHertel hi, I apologizes if i didnt state clearly in my question. In fact, i am still in the process of writing the code, and i find myself confusing in this for loop interpreting ... – j.l Apr 13 '16 at 04:31
  • @KunalPuri hi, thanks for commenting, i havent receive error in above code, and yet I am wondering how will this for loop iterative for d[1] and d[2] – j.l Apr 13 '16 at 04:32
  • Thanks for all of you. I have figured out the part already :) Have a nice day – j.l Apr 13 '16 at 05:03

2 Answers2

1

In R it is better to avoid for loops due to their poor performance. Since you are starting with a list lapply is a good start:

lapply(List_1, FUN=function(x){t.test(rgamma(25,x[1],1), rgamma(25,x[2],1))$p.value})

The apply function takes your list and then uses the gamma function on the 2 parameters within the t.test. The result will be a list of the five p values, one for each pair

Dave2e
  • 22,192
  • 18
  • 42
  • 50
1

Your code runs fine. I am actually not sure what you are asking here. You can just use print to find the iteratives, if that is what you want, like:

for (d in List_1){
  print(d[1])
  print(d[2])
}
fhlgood
  • 479
  • 4
  • 9