Create a new column in an R data set whose values are derived from other column values in the data set.

Hello dear R community,
I have a question about the "ifelse" command in R and if it is suitable for what I want to do. I have a column that shows the duration of a behavior (e.g. 00:00:02). In another column is listed if a stress behavior was shown (if a stress behavior was shown then this is marked with 1, if no behavior was shown then there is a 0 in the record). Now I would like to add a new column where, if a stress behavior was shown, the corresponding duration is entered. Correspondingly, if no stress behavior was shown, so a "0" is also entered for the duration.
I will try to make it a bit more understandable with a concrete example

Duration Stress
00:00:29.999 0
00:00:29.999 0
00:00:17.750 0
00:00:06.000 1
00:00:04.999 1
00:00:01.375 0
00:00:01.042 0
00:00:00.958 1
00:00:01.500 1
00:00:13.417 1
00:00:01.708 1

Table I would like to create at the end
Duration Stress Stress Duration
00:00:29.999 0 0
00:00:29.999 0 0
00:00:17.750 0 0
00:00:06.000 1 00:00:06.000
00:00:04.999 1 00:00:04.999
00:00:01.375 0 0
00:00:01.042 0 0
00:00:00.958 1 00:00:00.958
00:00:01.500 1 00:00:01.500
00:00:13.417 1 00:00:13.417
00:00:01.708 1 00:00:01.708

Can this be done with the "ifelse" command; if so, my question would be how or is there a more elegant solution?

Thanks in advance, I am really desperate.

Kind regards

Sarah

I think datatypes are relevant; i.e. if Duration is simply a character representation; probably ifelse is the way to go; otherwise if Duration was something a lubridate 'duration' type, simply multiplication (Duration * Stress), would get you there

Thank you for your helpful reply. I have managed it in the meantime. Unfortunately the times are available as character variables, which is my next problem.

I recommend that you investigate the lubridate package

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.