0

I have found a way to do the procedure I want to do, but I'm stuck on how to repeat that 100 or 1000 times.

Basically, I want to sample a random observation (indvd_ID) from each group (group_ID) in the dataset (flowers). Then I want to test whether the number of hits (No_hits) is higher on average for individuals of group A or group B, using a Mann-Whitney U test.

The code I wrote to do this is:

library(dplyr)

random_indvdIDs <- flowers %>% group_by(group_ID) %>% sample_n(1)
wilcox.test(random_indvdIDs$No_hits ~ random_indvdIDs$A_or_B)

I think I need to write a for loop, and then get it to print the p-value of the wilcox.test each time, but I'm struggling to do so!

I'm a bit of a noob so thanks very much to anyone who has an idea how to help. :)

tpetzoldt
  • 5,338
  • 2
  • 12
  • 29
Mairi
  • 35
  • 7
  • 1
    `replicate(1000, {...})`? – r2evans Jun 08 '21 at 17:53
  • @r2evans ah awesome thank you so much! It's printing the full readout of each test - may I ask if you know a quick way to print just the p-values, or put them into a data frame? Many thanks again! – Mairi Jun 08 '21 at 17:57
  • 1
    `sapply(replicate(1000, {...}, simplify = FALSE),getElement,"p.value")`? – Ian Campbell Jun 08 '21 at 18:08
  • @IanCampbell That's fantastic, thank you very much! – Mairi Jun 08 '21 at 18:13
  • @IanCampbell I'm sorry to be cheeky and ask another question, but do you know how I could save the getElement vector as a named object? I'd like to do a few further things with the set of p-values. – Mairi Jun 08 '21 at 18:20
  • You mean something other than `result <- ...`? – Ian Campbell Jun 08 '21 at 18:29
  • @IanCampbell er that sounds like what I'm going for but I'm afraid I don't know where to place it! – Mairi Jun 08 '21 at 18:50
  • The assignment operator comes in two versions `<-` and `->`. So you can put it at the very beginning or you can put it at the end. Either way, the arrow needs to point *from* the thing you want to assign *to* the name (symbol) you want to assign it to. – Ian Campbell Jun 08 '21 at 18:52
  • @IanCampbell I see what I did wrong now, I was just silly and put it inside the replicate function! That's really helpful of you, thank you very much. – Mairi Jun 08 '21 at 18:56

0 Answers0