Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding a new conditional column to a dataframe

I wonder if the following is possible in R?

I want to add a new column to my Data called task whose values are to be determined
by the following statements:

  • IF order is "sc", task value for rows with odd-numbered time values (1,3,…) is "simple" otherwise "complex".

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

  • IF order is "cs", task value for rows with odd-numbered time values (1,3,…) is "complex" otherwise "simple".

Data = read.table(text="
id order  time task
1  sc     1    x
1  sc     2    x
2  cs     1    x
2  cs     2    x
3  sc     1    x
3  sc     2    x
4  cs     1    x
4  cs     2    x
", h= TRUE)

>Solution :

You can use ifelse and time %% 2 to determine odd or even.

Data |>
  transform(task = ifelse(order == 'sc' & time %% 2 == 1 |
                          order == 'cs' & time %% 2 == 0,
                          'simple', 'complex'))

  id order time    task
1  1    sc    1  simple
2  1    sc    2 complex
3  2    cs    1 complex
4  2    cs    2  simple
5  3    sc    1  simple
6  3    sc    2 complex
7  4    cs    1 complex
8  4    cs    2  simple
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading