Following this question How to divide between groups of rows using dplyr?.
If I have this data frame:
id = c("a","a","b","b","c","c")
condition = c(0,1,0,1,0,1)
gene1 = sample(1:100,6)
gene2 = sample(1:100,6)
#...
geneN = sample(1:100,6)
df = data.frame(id,condition,gene1,gene2,geneN)
I want to group by id and divide the value of rows with condition == 0 with those with condition == 1 to get this :
df[condition == 0,3:5]/ df[condition == 1,3:5]
#
gene1 gene2 geneN
1 0.2187500 0.4946237 0.3750000
3 0.4700000 0.6382979 0.5444444
5 0.7674419 0.5471698 2.3750000
I can use dplyr as follows:
df %>%
group_by(id) %>%
summarise(gene1 = gene1[condition == 0] / gene1[condition == 1],
gene2 = gene2[condition == 0] / gene2[condition == 1],
geneN = geneN[condition == 0] / geneN[condition == 1])
But I have e.g. 100 variables such as below. How can I do that without having to list all the genes.
id = c("a","a","b","b","c","c")
condition = c(0,1,0,1,0,1)
genes = matrix(1:600,ncol = 100)
df = data.frame(id,condition,genes)