0

I would like to use R to create a new column in my data frame whose elements depend on a certain condition. For example, if my element respects condition A, then the value assigned will be A. If my element respects condition B then the value assigned will be B. If my element respects condition C then the value assigned will be C.

I know how to create such a structure for two conditions with the if_else structure, which allows to say that if the element respects condition A, then it will have the value A, otherwise the value B. However, I don't know how to do this for three elements A, B, C.

Using the if, else if, else structure doesn't work because it gives me the error "Error in if (condition) { : the condition has length > 1" because I can't use vectors in condition.

Does anyone have a solution to solve this problem in the general case? Thanks a lot !

  • 2
    This will be much easier to answer if you [make the question reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) by including a small representative dataset in a plain text format - for example the output from `dput(yourdataframe)`, if that is not too large. Also include code that you have tried and an indication of the desired output. – neilfws Jan 16 '23 at 23:55

1 Answers1

1

you can use case_when function from dplyr package

mutate(df, x=case_when(element1=='something' ~ A,
                       element2=='something' ~ B,
                       element3=='something' ~ C))
jkatam
  • 2,691
  • 1
  • 4
  • 12