1

A brief version of my df is like the following:

A <- c(10,50,50,10,60,70,50,20,60,10)
B <- c(0,3,2,4,1,3,5,1,1,2)
df<- data.frame(A,B)
df
A   B   
10  0
50  3
50  2
10  4
60  1
70  3
50  5
20  1
60  1
10  2

I want to generate an output C based on some conditions of column A and values in column B.

Conditions:

  1. C=0 when A < 50 or A "just becomes" >= 50
  2. C= abs(B[n+1] - B[n]) when both B[n+1] and B[n] are >= 50

Here is an example of what I want in column C:

A   B   C   Explaination
10  0   0    A <50, so C=0
50  3   0    A just becomes >= 50, so C is still 0
50  2   1    We have two consecutive A >= 50, so C = abs(2-3) = 1
10  4   0    A <50, so C=0
60  1   0    A just becomes >= 50, so C is still 0
70  3   2    We have two consecutive A >= 50, so C = abs(3-1) = 2
50  5   2    consecutive rows with A >= 50, so C = abs(5-3) = 2
20  1   0    A <50, so C=0
60  1   0    A just becomes >= 50, so C is still 0
10  2   0    A <50, so C=0

2 Answers 2

1

here's one option, though the logic is a little long-winded:

df$C <- ifelse(df$A < 50 | (df$A >= 50 & c(0, head(df$A, -1)) < 50) ,
               0, c(NA, abs(diff(df$B))))

Explanation:

  • I started with ifelse(df$A < 50, 0, c(NA, abs(diff(df$B)))). This gives a 0 if A < 50 and the differences of the Bs otherwise (diff(B) is one element shorter than B itself so I stick a NA on the front).
  • However this doesn't account for when A first exceeds 50, where the value should be 0 still. Note c(0, head(df$A, -1)) is just elements 2:end of the A column with a 0 stuck on front - it is the "previous" value of A. So if df$A >= 50 and the previous value is < 50, then this is the first time we have surpassed 50 and we should get the value 0.

I am sure there are other ways to do it too.

Sign up to request clarification or add additional context in comments.

Comments

0
library(dplyr)
df%>%mutate(C=ifelse(A<50,0,(ifelse(A>=50 & lag(A)>=50,abs(B-lag(B)),0))))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.