Greg T.D.
Greg T.D.

Reputation: 49

Take difference between two levels of factor variable while retaining other factor variables in R

I have a data table in R that looks like:

Gene Population Color Coverage
A_1 PopA Blue 0.016
A_1 PopA Green 0.022
A_1 PopB Blue 0.1322
A_1 PopB Green 0.552
A_2 PopA Blue 0.13
A_2 PopA Green 0.14
A_2 PopB Blue 1
A_2 PopB Green 0.9

I would like to take the difference between the different colors (blue and green), but only within the same Gene and Population. Ultimately I'd like to output a table that looks like this:

Gene Population Coverage
A_1 PopA -0.006
A_1 PopB -0.4198
A_2 PopA -0.01
A_2 PopB 0.1

I've been using the summarySE() function from Rmisc to get the averages i indicate above, but am unclear how I would compute something like the difference between values.

Thank you!

Upvotes: 0

Views: 692

Answers (1)

kath
kath

Reputation: 7724

One option with dplyr would be

library(dplyr)

my.df %>% 
  group_by(Gene, Population) %>% 
  summarize(Coverage = Coverage[Color == "Blue"] - Coverage[Color == "Green"])

# A tibble: 4 x 3
# Groups:   Gene [?]
#   Gene  Population Coverage
#   <fct> <fct>         <dbl>
# 1 A_1   PopA       -0.00600
# 2 A_1   PopB       -0.420  
# 3 A_2   PopA       -0.01   
# 4 A_2   PopB        0.100 

Data

my.df <- 
  structure(list(Gene = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), .Label = c("A_1", "A_2"), class = "factor"), 
                 Population = structure(c(1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L), .Label = c("PopA", "PopB"), class = "factor"), 
                 Color = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L), .Label = c("Blue", "Green"), class = "factor"), 
                 Coverage = c(0.016, 0.022, 0.1322, 0.552, 0.13, 0.14, 1, 0.9)), class = "data.frame", row.names = c(NA, -8L))

Upvotes: 2

Related Questions