So, I want to add a new column to my existing data. I have a condition column in my data of A,B, and C. I want to create a new column called Treated where e.g. condition A= treated, and condition B and C= non treated and add this to my data. I tried to do this with mutate function but I cannot do this. If you guys can recommend any function or argument I could use to do this would be very much appreciated. Thank you in advance
Asked
Active
Viewed 425 times
0
-
1please provide some example data using `dput` function to see the class of each column – danlooo Apr 27 '22 at 12:27
-
1Does this answer your question? [dplyr mutate with conditional values](https://stackoverflow.com/questions/22337394/dplyr-mutate-with-conditional-values), See also: https://stackoverflow.com/q/24459752/10264278 – Paul Apr 27 '22 at 12:28
-
1Welcome to StackOverflow! Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). This will make it much easier for others to help you. – Sotos Apr 27 '22 at 12:28
1 Answers
0
As you mention mutate
in your question, here is an idea with tidyverse-based functions:
tibble::tibble(cond = c("A", "B", "A", "C", "C")) |> # creates a dummy data set
dplyr::mutate(Treated = dplyr::case_when(cond %in% c("B", "C") ~ "non treated",
cond == "A" ~ "treated"))
#> # A tibble: 5 x 2
#> cond Treated
#> <chr> <chr>
#> 1 A treated
#> 2 B non treated
#> 3 A treated
#> 4 C non treated
#> 5 C non treated
Created on 2022-04-27 by the reprex package (v2.0.1)
You can also get the same result using ifelse()
.

Paul
- 2,850
- 1
- 12
- 37