R/Genetic_variability_parameters.R

Defines functions Genetic_variability_parameters

Genetic_variability_parameters <- function(data) {

  # Convert the first two columns to factor type

  data[, 1:2] <- lapply(data[, 1:2], as.factor)

  # Convert the remaining columns to numeric

  data[, -c(1, 2)] <- lapply(data[, -c(1, 2)], as.numeric)

  # Extract trait names (excluding the first two columns)

  traits <- names(data)[-c(1, 2)][sapply(data[-c(1, 2)], is.numeric)]

  results <- data.frame(Parameter = c("Grand Mean", "Phenotypic Variance", "Genotypic Variance",

                                      "Phenotypic Coefficient of Variation ( % )", "Genotypic Coefficient of Variation ( % )",

                                      "Broad-Sense Heritability ( % )", "Genetic Advance", "Genetic Advance as Percentage of Mean ( % )", "Standard Error of Mean"),
                        stringsAsFactors = FALSE)


  for (i in 1:length(traits)) {

    trait <- traits[i]


    # Perform linear regression

    formula <- as.formula(paste0("`", trait, "` ~ `", names(data)[1], "` + `", names(data)[2], "`"))

    model <- lm(formula, data = data)

    # Perform ANOVA

    anova_result <- anova(model)

    # Calculate means

    grand_mean <- mean(data[[trait]])

    replication_levels <- nlevels(data[[1]])

    # Calculate genotypic variance

    genotypic_variance <- round((anova_result$`Mean Sq`[2] - anova_result$`Mean Sq`[3]) / replication_levels,4)

    # Calculate phenotypic variance

    phenotypic_variance <- round(genotypic_variance + anova_result$`Mean Sq`[3],4)


    # Calculate coefficients of variation

    phenotypic_coefficient_of_variation <- round((sqrt(phenotypic_variance) / grand_mean) * 100,4)

    genotypic_coefficient_of_variation <- round((sqrt(genotypic_variance) / grand_mean) * 100,4)


    # Calculate heritability

    heritability <- round((genotypic_variance / phenotypic_variance) * 100,4)


    # Calculate genetic advance

    genetic_advance <- round((genotypic_variance / sqrt(phenotypic_variance)) * 2.06,4)


    # Calculate genetic advance as percentage of mean

    genetic_advance_as_percentage_of_mean <- round((genetic_advance / grand_mean) * 100,4)


    # Calculate standard error of mean

    standard_error_of_mean <- round(sqrt(anova_result$`Mean Sq`[3] / replication_levels),4)


    # Store results in data frame

    results[[trait]] <- c(grand_mean, phenotypic_variance, genotypic_variance,

                          phenotypic_coefficient_of_variation, genotypic_coefficient_of_variation,

                          heritability, genetic_advance, genetic_advance_as_percentage_of_mean,

                          standard_error_of_mean)
  }


  # Return the results
  return(results)
}

Try the TBA package in your browser

Any scripts or data that you put into this service are public.

TBA documentation built on June 8, 2025, 1:07 p.m.