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-numberedtime
values (1,3,...) is"simple"
otherwise"complex"
.IF
order
is"cs"
,task
value for rows with odd-numberedtime
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)
CodePudding user response:
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
CodePudding user response:
The other answer by Darren Tsai is great! I'm not sure what the speed of ifelse()
is like, I don't have much experience using it, but here's an alternate option:
All it does is get the row numbers (via which()
) that match the conditions for the "simple"
case and then again for "complex"
case.
index.simple <- which( (Data$order=="sc" & Data$time%%2==1) | (Data$order=="cs" & Data$time%%2==0) )
Data$task[index.simple] <- "simple"
index.complex <- which( (Data$order=="sc" & Data$time%%2==0) | (Data$order=="cs" & Data$time%%2==1) )
Data$task[index.complex] <- "complex"