Paulin Reboul
Paulin Reboul

Reputation: 35

Dividing row by row beneath it in R

I have a data frame like so :

block partner prSwitch
1   p1  0.06666667
1   p2  0.06666667
2   p1  0.03333333
2   p2  0.06666667
3   p1  0.10000000
3   p2  0.06666667
4   p1  0.06666667
4   p2  0.03333333
5   p1  0.10000000
5   p2  0.13333333
6   p1  0.06666667
6   p2  0.23333333

I would like to divide each row with p1 with the one with p2 in the same block and that for every block.

I'd like my new df to look like this :

block  prSwitch of p1/p2
1   0.06666667
2   0.03333333
3   0.10000000
4   0.06666667
5   0.10000000
6   0.06666667

Thank you !

Upvotes: 1

Views: 38

Answers (3)

Roland
Roland

Reputation: 132706

Reshape your data to wide format. This will also work nicely if either a p1 or p2 value is missing.

DF <- read.table(text = "block partner prSwitch
1   p1  0.06666667
1   p2  0.06666667
2   p1  0.03333333
2   p2  0.06666667
3   p1  0.10000000
3   p2  0.06666667
4   p1  0.06666667
4   p2  0.03333333
5   p1  0.10000000
5   p2  0.13333333
6   p1  0.06666667
6   p2  0.23333333", header = TRUE)

library(reshape2)
DF1 <- dcast(DF, block ~ partner)
DF1$quotient <- DF1$p1 / DF1$p2
#  block         p1         p2  quotient
#1     1 0.06666667 0.06666667 1.0000000
#2     2 0.03333333 0.06666667 0.4999999
#3     3 0.10000000 0.06666667 1.4999999
#4     4 0.06666667 0.03333333 2.0000003
#5     5 0.10000000 0.13333333 0.7500000
#6     6 0.06666667 0.23333333 0.2857143

Upvotes: 0

Daniel O
Daniel O

Reputation: 4358

In Base R we could use this

new_df <- data.frame(
    block = unique(df$block),
    "prSwitch of p1/p2" = sapply(split(df, df$block), function(x) x$prSwitch[1] / x$prSwitch[2]) 
)

> new_df
  block prSwitch.of.p1.p2
1     1         1.0000000
2     2         0.4999999
3     3         1.4999999
4     4         2.0000003
5     5         0.7500000
6     6         0.2857143

Upvotes: 0

Gregor Thomas
Gregor Thomas

Reputation: 145775

Using dplyr:

library(dplyr)
your_data %>%
  group_by(block) %>%
  summarize(prSwitch_p1_p2_ratio = prSwitch[partner == "p1"] / prSwitch[partner == "p2"])

This will throw an error if you don't have a single p1 and p2 within a block.

Upvotes: 2

Related Questions