0

I am attempting to assign values to a column based on conditional statements but the POSIXct format seems to be throwing me off. I have a column of times and would like to assign them to day/night/dawn/dusk with something like this:

if(t40636$time>t40636$dawn.b&t40636$time<t40636$dawn.e){
  t40636$time.periods=1
} else {
  if(t40636$time>t40636$mid.day.b&t40636$time<t40636$mid.day.e){
    t40636$time.periods=2
  } else {
    if(t40636$time>t40636$dusk.b&t40636$time<t40636$dusk.e){
      t40636$time.periods=3
    } else {
      if(t40636$time>t40636$mid.night.b&t40636$time<t40636$mid.night.e){
        t40636$time.periods=4
        } else {
          t40636$time.periods=0
        }
    }
  }
}

However, this code does not work because of the format of the columns and yields the matrix seen below (only 0s in the time.periods column).

     Date Temp..ºC. Depth..m. Light  time time.at.depth dawn.b dawn.e dusk.b
1 2012-06-19     14.47     -21.5   255 15:32             0  01:42  04:42  19:13
2 2012-06-19     16.99     -20.2   255 15:37             5  01:42  04:42  19:13
3 2012-06-19     12.60     -18.8   255 15:41             4  01:42  04:42  19:13
4 2012-06-19     16.36     -17.5   255 15:46             5  01:42  04:42  19:13
5 2012-06-19     16.36     -13.4   255 15:51             5  01:42  04:42  19:13
6 2012-06-19     17.94      -2.7   255 15:56             5  01:42  04:42  19:13
  dusk.e mid.day.b mid.day.e mid.night.b mid.night.e time.periods
1  22:13     10:27     13:27       22:27       01:27            0
2  22:13     10:27     13:27       22:27       01:27            0
3  22:13     10:27     13:27       22:27       01:27            0
4  22:13     10:27     13:27       22:27       01:27            0
5  22:13     10:27     13:27       22:27       01:27            0
6  22:13     10:27     13:27       22:27       01:27            0

ifelse yields something close to what I want but I can't do multiple statements with it. Any suggestions are greatly appreciated.

t40636$time.periods=ifelse(t40636$time>t40636$dawn.b&t40636$time<t40636$dawn.e,1,0)
4

1 回答 1

0

“修复我的多个 if-else 语句”的答案几乎总是“不要使用多个 if-else 结构”。

R 语言有一个很好的switch功能,它的帮助页面有一些很好的例子。

于 2013-01-28T19:41:39.897 回答