Adding a new conditional column to a dataframe

Advertisements

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".

  • 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

Leave a ReplyCancel reply