1

I want to write/apply a function that repeats the LD2 function from the pegas package on a dataset (jaguar), but changes the value of the 'locus' argument each time. The 'locus' argument accepts a vector of length two (e.g. c(1,2), c(2,3), c(77,78), etc.).

For example, I want the code to run loci.pairs[[1]], then loci.pairs[[2]], loci.pairs[[3]], etc. and output the results as a list.

I have tried doing this with lapply, for loops and while loops but have run into errors (see below):

Load libraries and data

library(adegenet)
library(pegas)
data("jaguar")

Create a list of pairs of loci

loci.pairs = combn(seq(1,ncol(jaguar)-1), 2, simplify = FALSE)
loci.pairs[[1]]

Compare each pair of loci from loci.pairs list

LD2(jaguar, locus=c(1,2), details=FALSE)
LD2(jaguar, locus=loci.pairs[[1]], details=FALSE)
LD2(jaguar, locus=loci.pairs[[2]], details=FALSE)
LD2(jaguar, locus=loci.pairs[[3]], details=FALSE)
LD2(jaguar, locus=loci.pairs[[4]], details=FALSE)
LD2(jaguar, locus=loci.pairs[[78]], details=FALSE)

lapply (error)

lapply(jaguar, function(x) LD2(jaguar, locus=loci.pairs[[x]], details=FALSE))

Error in loci.pairs[[x]] : recursive indexing failed at level 2

AndrewGB
  • 16,126
  • 5
  • 18
  • 49
Tom__Jenkins
  • 129
  • 6
  • you could maybe try `sapply(1:number_of_pairs,function(x) LD2(jaguar,locus=loci.pairs[[x]],details=FALSE` – boski Apr 24 '19 at 09:35

1 Answers1

2

the lapply function has a different syntax. Try this:

lapply(loci.pairs, function(x) LD2(jaguar, locus=x, details=FALSE))

The first argument of lapply contains the list which you want to iterate over. Since you want to iterate over the combinations you have to use lapply(loci.pairs...) instead of lapply(jaguar,...).

Essentially, this call to lapply is (in terms of output) equivalent to the following loop:

result_list = list()
for (i in 1:n) {
   result_list[[i]] <-  LD2(jaguar, locus=loci.pairs[[i]], details=FALSE)
}
Cettt
  • 11,460
  • 7
  • 35
  • 58