Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if value of column A is present in the same row or previous rows of column B

I have this dataframe:

df <- structure(list(A = 1:5, B = c(1L, 5L, 2L, 3L, 3L)), 
                class = "data.frame", row.names = c(NA, -5L))

  A B
1 1 1
2 2 5
3 3 2
4 4 3
5 5 3

I would like to get this result:

  A B Result
1 1 1      B
2 2 5   <NA>
3 3 2   <NA>
4 4 3   <NA>
5 5 3      B

Strategy:

  1. Check if A==B then assign B to new column Result if not NA.
  2. But do this also for all PREVIOUS rows of B.

AIM:

I want to learn how to check if a certain value of column A say in row 5 is in the previous rows of column B (eg. row 1-4).

like image 516
TarJae Avatar asked Dec 18 '22 11:12

TarJae


1 Answers

I hope the following code fits your general cases

transform(
  df,
  Result = replace(rep(NA, length(B)), match(A, B) <= seq_along(A), "B")
)

which gives

  A B Result
1 1 1      B
2 2 5   <NA>
3 3 2   <NA>
4 4 3   <NA>
5 5 3      B
like image 64
ThomasIsCoding Avatar answered May 24 '23 07:05

ThomasIsCoding