Due Wednesday, April 12 at 9 AM

Assignment Goals

The goals of this assignment are to:

  1. Learn how to use lm() to create linear regressions on both categorical and numerical independent variables
  2. Practice ANOVA and explore the relationship between ANOVA and linear regression

Assignment Part 1: Data Exploration and ANOVA

In this assignment, you will use simulated gene expression data, generated to be similar to the type of data from Gymrek et al. 2016 that we’ve been discussing in class (and have used in previous assignments).

The data has genotype data on a SNP near a gene, as well as on the number of repeat copies in a microsatellite repeat located inside the enhancer region. It also has data on the expression of the gene.

1A. Load in Assignment_9_Expression_data.csv as expression_df. Plot expression as a function of microsatellite repeat number (microsat_repeats), coloring by SNP_genotype. Note that you will need to convert the SNP_genotype column into a factor type in order for plot coloring to work.

#Loaded in data and plotted expression and microsatellite repeats.

# read in data
expression_df <- read.csv('Assignment_9_Expression_data.csv')
# convert SNP_genotype to factor
expression_df$SNP_genotype <- factor(expression_df$SNP_genotype)
# plot
plot(expression_df$microsat_repeats, expression_df$expression, col = expression_df$SNP_genotype)

1B. Write a function, mean_se_fun(), that takes in a vector of values v and returns a vector containing the mean, variance, and sample size of those values. Use this function to calculate the mean, variance, and sample size of the expression column in expression_df; save the mean to a variable called tot_mean, the variance to a variable called tot_var, and the sample size to a variable called tot_n. Print tot_mean, tot_var, and tot_n.

#Wrote a function that will output mean, variance, and sample size of my input, then used it to find those values for expression.

mean_se_fun <- function(v){
  mean_v <- mean(v)
  var_v <- var(v)
  sample_size_v <- length(v)
  vector <- c(mean_v, var_v, sample_size_v)
  return(vector)
}
mean_se_fun(expression_df$expression)
## [1]  4.5193620  0.8664899 90.0000000
tot_mean = mean_se_fun(expression_df$expression)[1]
tot_var = mean_se_fun(expression_df$expression)[2]
tot_n = mean_se_fun(expression_df$expression)[3]
print(tot_mean)
## [1] 4.519362
print(tot_var)
## [1] 0.8664899
print(tot_n)
## [1] 90

1C. Create a new dataframe, SNP_group_df, with a SNP_genotype column, which should contain the unique values of the SNP_genotype column from expression_df, and three columns containing NAs: group_mean, group_var, and group_n. Your dataframe should have 3 rows and 4 columns.

Loop through the rows of SNP_group_df; for each row, get the value of the SNP_genotype column corresponding to that row, subset expression_df to only include data from that genotype, and use mean_se_fun() to calculate the mean, variance, and sample size of expression for individuals with that genotype. Save each these values to their respective group... columns in SNP_group_df. You should end up with a filled dataframe that has the genotype, mean, variance, and sample size for each of those genotypes in each row. Print SNP_group_df.

#Created a new dataframe that found the mean gene expression, variance, and size of different allele groups. To do this I first generated an empty dataframe then made a loop to fill in all of the values by row.

SNP_genotype = unique(expression_df$SNP_genotype)
group_mean = c()
group_var = c()
group_n = c()

SNP_group_df <- data.frame(matrix(nrow = 3, ncol = 4))
colnames(SNP_group_df) = c("SNP_genotype", "group_mean", "group_var", "group_n")
SNP_group_df$SNP_genotype = SNP_genotype

for (c in 1:3){
  genotype = c("CC", "AC", "AA")
  subset = subset(expression_df$expression, expression_df$SNP_genotype==genotype[c])
  output = mean_se_fun(subset)
  SNP_group_df$group_mean[c] = output[1]
  SNP_group_df$group_var[c] = output[2]
  SNP_group_df$group_n[c] = output[3]
}
print(SNP_group_df)
##   SNP_genotype group_mean group_var group_n
## 1           CC   3.918518 0.3216969      50
## 2           AC   4.986754 0.2955444      30
## 3           AA   6.121404 0.2793289      10

1D. UNGRADED If two dataframes share a column name (as SNP_group_df and expression_df do, for the SNP_genotype column), we can use the merge() function to merge them based on the values in this column. Here, we are merging SNP_group_df and expression_df, which should result in a new dataframe (which we assign to expression_df_group_info) that has the group mean, variance, and sample size for every genotype listed in its corresponding row.

expression_df_group_info <- merge(expression_df, SNP_group_df)
head(expression_df_group_info)

1E. In ANOVA, the group means of every group can be thought of as the best prediction for the individual’s dependent variable value (here, expression level). To calculate how much each individual’s expression level deviates from this level, we can simply subtract their expression level from the predicted value (this is calculating the residuals, or errors). Create a new column in expression_df_group_info, error, which will contains the difference between an individual’s actual expression value and their predicted expression value based on group (group_mean). Print the first six rows of expression_df_group_info. (You’re basically calculating the ‘epsilon_i’ term we talked about in class for every individual within every group).

#Created a new column in expression_df_group_info to find the difference between actual and expected value, or the error term.

expression_df_group_info$error = (expression_df_group_info$expression - expression_df_group_info$group_mean)
head(expression_df_group_info)

1F. We have already calculated the total variance in expression level above. Calculate the variance of the error values in expression_df_group_info and save it to a variable called err_var. Calculate the variance of the predicted values across all individuals and save it to a variable predicted_var. Print out err_var, predicted_var, the sum of these two variances, and the total variance in expression calculated above. Think about what you notice in these numbers. Finally, calculate and print the R-squared of this data (think about what that would be).

#Since the group mean expresses what we think the expression will be based on genotype, we use the group mean to find our predicted variance term. The sum of this variance and the error variance will equal the total variance, which then allows us to calculate r squared by doing predicted_var/tot_var.

err_var = var(expression_df_group_info$error)
predicted_var = var(expression_df_group_info$group_mean)
print(err_var)
## [1] 0.3016618
print(predicted_var)
## [1] 0.5648282
print(err_var + predicted_var)
## [1] 0.8664899
print(tot_var)
## [1] 0.8664899
r_sq = predicted_var / tot_var
print(r_sq)
## [1] 0.6518577

1G. Run ANOVA on the expression data to determine whether SNP_genotype affects expression level. Print a summary of the anova model output (using the summary() function).

#Here we run anova as instructed.

expression_anova <- aov(expression_df_group_info$expression ~ expression_df_group_info$SNP_genotype, data = expression_df_group_info)
summary(expression_anova)
##                                       Df Sum Sq Mean Sq F value Pr(>F)    
## expression_df_group_info$SNP_genotype  2  50.27  25.135   81.45 <2e-16 ***
## Residuals                             87  26.85   0.309                   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Assignment Part 2: Categorical and numeric linear models

2A. Repeat the analysis above, but now using lm() to regress expression level on SNP_genotype. Print the model output using summary(). NOTE that here, because our SNP_genotype column is a categorical, not numerical, we are using each genotype as its own group, rather than taking into account the fact that heterozygotes may have intermediate phenotypes to homozygotes. Think about how the R-squared and group means calculated above compare to the R-squared and coefficients calculated by the model.

#Here we run the same analysis as the previous anova but using a linear model lm().

lm_result <- lm(expression_df_group_info$expression ~ expression_df_group_info$SNP_genotype, data = expression_df_group_info)
summary(lm_result)
## 
## Call:
## lm(formula = expression_df_group_info$expression ~ expression_df_group_info$SNP_genotype, 
##     data = expression_df_group_info)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -1.06964 -0.37543 -0.08536  0.33169  1.36634 
## 
## Coefficients:
##                                         Estimate Std. Error t value Pr(>|t|)
## (Intercept)                               6.1214     0.1757  34.846  < 2e-16
## expression_df_group_info$SNP_genotypeAC  -1.1346     0.2028  -5.594 2.53e-07
## expression_df_group_info$SNP_genotypeCC  -2.2029     0.1924 -11.447  < 2e-16
##                                            
## (Intercept)                             ***
## expression_df_group_info$SNP_genotypeAC ***
## expression_df_group_info$SNP_genotypeCC ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.5555 on 87 degrees of freedom
## Multiple R-squared:  0.6519, Adjusted R-squared:  0.6439 
## F-statistic: 81.45 on 2 and 87 DF,  p-value: < 2.2e-16

2B. Now, we are going to regress expression level on the number of copies of the microsatellite repeat in the enhancer, microsat_repeats. Run a linear model doing this, and save the output to a variable, microsat_model. Print a summary of microsat_model. Note that the coefficients of an lm() output can be easily accessed: print microsat_model$coefficients.

microsat_model <- lm(expression_df_group_info$expression ~ expression_df_group_info$microsat_repeats, data = expression_df_group_info)
summary(microsat_model)
## 
## Call:
## lm(formula = expression_df_group_info$expression ~ expression_df_group_info$microsat_repeats, 
##     data = expression_df_group_info)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -1.61043 -0.56692 -0.04548  0.60042  2.20224 
## 
## Coefficients:
##                                           Estimate Std. Error t value Pr(>|t|)
## (Intercept)                                0.09385    0.78345   0.120    0.905
## expression_df_group_info$microsat_repeats  0.05843    0.01028   5.682  1.7e-07
##                                              
## (Intercept)                                  
## expression_df_group_info$microsat_repeats ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.8007 on 88 degrees of freedom
## Multiple R-squared:  0.2684, Adjusted R-squared:  0.2601 
## F-statistic: 32.28 on 1 and 88 DF,  p-value: 1.698e-07
print(microsat_model$coefficients)
##                               (Intercept) 
##                                0.09384526 
## expression_df_group_info$microsat_repeats 
##                                0.05842695

2C. Create a function, microsat_regress(), that takes in a dataframe and runs a regression of the expression column of that dataframe on the microsat_repeats column. microsat_regress() should return a vector containing the intercept and microsat_repeats slope. Run microsat_regress() on expression_df, save the output to a vector called microsat_coef, and print microsat_coef. The results should be the same as when you printed microsat_model$coefficients above.

#Here I define a function to take a dataframe, d, as its input, and then find the coefficients from the linear regression data.

microsat_regress <- function(d){
  data_f <- lm(d$expression ~ d$microsat_repeats, data = d)
  summary(data_f)
  return(data_f$coefficients)
}
microsat_coef = c()
microsat_coef <- microsat_regress(expression_df)
print(microsat_coef)
##        (Intercept) d$microsat_repeats 
##         0.09384526         0.05842695

2D. Create a new column in expression_df_group_info called microsat_predict. In this column, use microsat_coef and expression_df_group_info$microsat_repeats to calculate the predicted expression level in each individual based on the number of microsatellite repeats only. Remember that this depends on an intercept, a slope, and an independent variable value, which we have. Print the first 6 rows of your dataframe. NOTE: you shouldn’t need a loop to do this; you can multiply the appropriate column by the slope directly, and/or add a number to a column, and it will produce a vector of values.

#Here I put the values from the previous section and input them into slope intercept equation to define the new column.

expression_df_group_info$microsat_predict = (microsat_coef[1] + expression_df_group_info$microsat_repeats*microsat_coef[2])
head(expression_df_group_info)

2E. Calculate the variance in expression accounted for by microsatellite repeat number (the variance of expression_df_group_info$microsat_predict) and save it to a variable, microsat_predict_var. Print this variable, and calculate and print the R-squared of the microsatellite-only model. Think about how this R-squared compares to the R-squared calculated by the linear model in 2B.

#Here I again find the variance predicted by the linear model and then use that to find the R squared.

microsat_predict_var = var(expression_df_group_info$microsat_predict)
print(microsat_predict_var)
## [1] 0.2325588
r_sq_ms = microsat_predict_var / tot_var
print(r_sq_ms)
## [1] 0.2683918

Assignment Part 3: Simpson’s Paradox

Before you start this part, think carefully about the plot of microsatellite repeat numbers vs expression levels colored by groups that you made in 1A. Think about which way microsatellite repeat number seems to affect expression level (does more repeats correspond to higher or lower expression level), and what the sign on the slope for microsatellite repeat number should be (positive or negative). Compare this to the actual slope for microsatellite repeat number calculated in 2B. If you’re thinking about this the right way, the signs on those slopes shouldn’t match. Think about why that happens.

3A. We’re going to calculate the slopes associated with microsatellite repeat number in each genotype separately. Create a column called microsat_group_slope in SNP_group_df. Similar to 1C above, loop through the rows of SNP_group_df; for each row, get the value of the SNP_genotype column corresponding to that row, subset expression_df to only include data from that genotype, and this time, use microsat_regress() to calculate the intercept and slope associated with microsatellite repeat number for that subset. Save just the slope value to the microsat_group_slope (in the correct row) of SNP_group_df. Print the microsat_group_slope column of SNP_group_df.

#Here I modified the loop from 1C, changing how I made the subset so that it would produce a dataframe rather than a vector, since microsat_regress requires a dataframe to be input. Now that the values are in a dataframe, the function runs according to the loop to print the values we want.

for (c in 1:3){
  genotype = c("CC", "AC", "AA")
  subset_df = expression_df[expression_df$SNP_genotype==genotype[c], ]
  output_1 = microsat_regress(subset_df)
  SNP_group_df$microsat_group_slope[c] = output_1[2]
}
print(SNP_group_df$microsat_group_slope)
## [1] -0.06989432 -0.04628442 -0.05309100

Think about how the slopes calculated here compare to your expected effect of the microsatellite repeat number on expression level, and to the slope calculated above in 2B.

3B. The procedure above calculated a separate slope corresponding to the effect of microsatellite repeat number within each group. We can run a linear model to calculate a common within-group slope for the effect of microsatellite repeat number. Use lm() to regress expression level on both SNP_genotype and microsat_repeats. Print a summary of this model.

#Here we combine the linear model to account for SNP_genotype and microsat_repeats combined effect on expression.

combined_model <- lm(expression_df$expression ~ expression_df$SNP_genotype + expression_df$microsat_repeats, data = expression_df)
summary(combined_model)
## 
## Call:
## lm(formula = expression_df$expression ~ expression_df$SNP_genotype + 
##     expression_df$microsat_repeats, data = expression_df)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -0.7878 -0.3746 -0.1189  0.3263  1.3755 
## 
## Coefficients:
##                                Estimate Std. Error t value Pr(>|t|)    
## (Intercept)                    11.25981    1.03958  10.831  < 2e-16 ***
## expression_df$SNP_genotypeAC   -1.67062    0.20916  -7.987 5.61e-12 ***
## expression_df$SNP_genotypeCC   -3.32899    0.28244 -11.787  < 2e-16 ***
## expression_df$microsat_repeats -0.05722    0.01145  -4.999 3.00e-06 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.4918 on 86 degrees of freedom
## Multiple R-squared:  0.7302, Adjusted R-squared:  0.7208 
## F-statistic:  77.6 on 3 and 86 DF,  p-value: < 2.2e-16

Think about the slope associated with microsatellite repears calculated by this model, and how it compares to the slopes calculated in 3A and 2B. Make sure you understand why this slope is different from the one in 2B. In addition, you can compare the R-squared values between the model in 3B, which includes the effects of both SNP genotype and microsatellite repeat number on expression, and the model in 2A, which includes only the effects of SNP genotype on expression level. Think about approximately what additional proportion of the total variance microsatellite repeat length accounts for once we account for variance in SNP genotype? (i.e. what is the difference between R-squared values in 2A and 3B)?