0

Say you have something like this where table A and B are just some values and table C is comprised of the biggest number between the two.

enter image description here

Firstly, I would like to know how to select all elements in column C where the value from the previous row (i.e. previous day) didn't come from the same column. So the 16, for example, wouldn't be selected as both itself and the previous value (22) come from column B, but the 22 would be selected.

Secondly, and more generally, what I'm trying to do are conditional probabilities so I'd like to calculate the probability in C of a value being chosen from a column, knowing that the previous value comes from the other column. So essentially, P(A|B happened in the previous observation), P(B|A happened in the previous observation), P(A|A happened in the previous observation) and P(B|B happened in the previous observation).

Thanks a lot for the help.

EDIT: As requested, here is a minimum reproducible example (I think). Thanks and pardon for the suboptimal code.

library(dplyr)

df <- data.frame(
 A = freeny$y,
 B = freeny$lag.quarterly.revenue
)

df$C <- case_when(
 as.numeric(df$A) >= as.numeric(df$B) ~ as.numeric(df$A),
 as.numeric(df$A) < as.numeric(df$B) ~ as.numeric(df$B)
)
Miguel
  • 89
  • 5
  • 2
    Please provide a minimum reproducible example: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – amrrs Nov 16 '17 at 09:48
  • Using data.table for first you can use `dt[, foo := max(A, B)]` followed by `dt[, c:= lag(foo)]`. For second case you can define `dt$foo_A <- ifelse(dt$A > dt$B, 1, 0)` and `dt$foo_B <- ifelse(dt$A < dt$B, 1, 0)` subsequently probabilities should be easy to calculate using `foo_A` and `foo_B` – abhiieor Nov 16 '17 at 10:02
  • However if either A happened in the previous observation i.e. `lag(foo_A)` or B happened in the previous observation i.e. `lag(foo_B)` will be true so not all probabilities could be calculated. How you want to handle that? – abhiieor Nov 16 '17 at 10:04
  • @amrrs there you go. – Miguel Nov 16 '17 at 10:51

0 Answers0