0

How to create a condition in R, if the value of variable A is equal to the same value of B (without indication of the value of variables A and B), then create a new variable (C) with a new value.

For example, if the value of A == B, then a new variable C.

The ifelse function requires indicating the values of A and B.

Newcomer
  • 7
  • 1
  • Hello @Lena, can you create a minimal working example and show the expected output? – markus Nov 08 '22 at 06:36
  • Does this answer your question? [Can dplyr package be used for conditional mutating?](https://stackoverflow.com/questions/24459752/can-dplyr-package-be-used-for-conditional-mutating) – maydin Nov 08 '22 at 06:36

1 Answers1

0

A == B creates a boolean, which you easily may coerce as.integer.

transform(dat, C=as.integer(A == B))
#   A B C
# 1 a b 0
# 2 a a 1
# 3 a b 0
# 4 a a 1
# 5 a b 0

Data:

dat <- data.frame(A=c('a', 'a', 'a', 'a', 'a'),
                  B=c('b', 'a', 'b', 'a', 'b'))
jay.sf
  • 60,139
  • 8
  • 53
  • 110