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:
A==B
then assign B
to new column Result
if not NA
.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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With