genind2df <- function (x, pop = NULL, sep = "", usepop = TRUE, oneColPerAll = FALSE, rm.incompleteGeno=F) { if (!is.genind(x)) stop("x is not a valid genind object") if (is.null(pop)) { pop <- x@pop } if (x@type == "PA") { res <- tab(x) if (usepop && !is.null(pop)) res <- cbind.data.frame(pop = pop(x), res) return(res) } kX <- seploc(x, res.type = "matrix") if (oneColPerAll & all(x@ploidy == x@ploidy[1])) { sep <- "/" } recod <- function(vec, lab) { if (any(is.na(vec))) return(NA) res <- paste(rep(lab, vec), collapse = sep) return(res) } kGen <- lapply(1:length(kX), function(i) apply(kX[[i]], 1, recod, x@all.names[[i]])) names(kGen) <- locNames(x) if (oneColPerAll) { if (all(x@ploidy == x@ploidy[1])) { f1 <- function(vec) { vec[is.na(vec)] <- paste(rep("NA", x@ploidy[1]), collapse = sep) return(vec) } temp <- lapply(kGen, f1) temp <- lapply(temp, strsplit, sep) ### added by Naoki to deal with genotypes when there are missing alleles if(! rm.incompleteGeno) { ## incomplete genotype is retained, and NA is used for the missing allleles adjustVectLength <- function(vect, fill, min.len) { return(c(vect,rep(fill, max(0, min.len - length(vect))))) } temp <- lapply(temp, function(l) lapply(l, adjustVectLength, fill="NA", min.len=x@ploidy[1])) } else { ## alleles of incomplete genotypes are replaced with NA checkVectLength <- function(vect, fill, len) { if (length(vect) != len) { return(rep(fill,len)) } else { return(vect) } } temp <- lapply(temp, function(l) lapply(l, checkVectLength, fill="NA", len=x@ploidy[1])) } ### end of addition res <- lapply(temp, function(e) matrix(unlist(e), ncol = x@ploidy[1], byrow = TRUE)) res <- data.frame(res, stringsAsFactors = FALSE) ### Naoki added this to replace character string "NA" with NA res[res == "NA"] <- NA ### end of addition names(res) <- paste(rep(locNames(x), each = x@ploidy[1]), 1:x@ploidy[1], sep = ".") if (!is.null(pop) & usepop) res <- cbind.data.frame(pop, res, stringsAsFactors = FALSE) rownames(res) <- indNames(x) return(res) } else { warning("All ploidies must be equal in order to separate the alleles.\nReturning one column per locus") } } res <- as.data.frame(do.call(cbind, kGen), stringsAsFactors = FALSE) rownames(res) <- indNames(x) colnames(res) <- locNames(x) if (!is.null(pop) & usepop) res <- cbind.data.frame(pop, res, stringsAsFactors = FALSE) return(res) }