R:用`ifelse()`嵌套

use*_*466 2 r

我有一个数据,从2007年7月1日到2014年10月5日.

我正在尝试创建一个名为month_index数据框的列,该列dat将随着年和月的增加而增加整数值.

我写了下面的R代码,但它看起来并不简约.

dat$month_index <- with(dat,
                          ifelse(Year == 2007 & Month == 7, 7, 
                                 ifelse(Year == 2007 & Month == 8, 8, 
                                        ifelse(Year == 2007 & Month == 9, 9, 
                                               ifelse (Year == 2007 & Month == 10, 10, 
                                                       ifelse(Year == 2007 & Month == 11, 11,
                                                              ifelse(Year == 2007 & Month == 12, 12,
                                                                     ifelse(Year == 2008 & Month == 1, 13,
                                                                            ifelse(Year == 2008 & Month == 2, 14, 
                                                                                   ifelse(Year == 2008 & Month == 3, 15,
                                                                                          ifelse(Year == 2008 & Month == 4, 16, 17))))))))
Run Code Online (Sandbox Code Playgroud)

如何在几行中执行代码?

Fra*_*ank 6

避免嵌套的最佳情况ifelse是代数解决方案.幸运的是,这可以在这里工作:

dat$month_index <- with(dat, Month + 12 * (Year - 2007))
Run Code Online (Sandbox Code Playgroud)