我怎么能把下面的循环放在R?

时间:2017-04-29 17:16:26

标签: r loops

WkD <- unique(MILKORDERS$WeekDay)
Wk <- unique(MILKORDERS$Week)
ctwkd <- length(unique(MILKORDERS$WeekDay))
ctwk <- length(unique(MILKORDERS$Week))

MILKORDERS$Wednesday_1[MILKORDERS$WeekDay=='Wednesday' & MILKORDERS$Week==1] <- 1
MILKORDERS$Wednesday_2[MILKORDERS$WeekDay=='Wednesday' & MILKORDERS$Week==2] <- 1
MILKORDERS$Wednesday_3[MILKORDERS$WeekDay=='Wednesday' & MILKORDERS$Week==3] <- 1
MILKORDERS$Wednesday_4[MILKORDERS$WeekDay=='Wednesday' & MILKORDERS$Week==4] <- 1

MILKORDERS$Thursday_1[MILKORDERS$WeekDay=='Thursday' & MILKORDERS$Week==1] <- 1
MILKORDERS$Thursday_2[MILKORDERS$WeekDay=='Thursday' & MILKORDERS$Week==2] <- 1
MILKORDERS$Thursday_3[MILKORDERS$WeekDay=='Thursday' & MILKORDERS$Week==3] <- 1
MILKORDERS$Thursday_4[MILKORDERS$WeekDay=='Thursday' & MILKORDERS$Week==4] <- 1

我想将上述内容放在循环中,并希望在一周的所有日子里都能做到。

1 个答案:

答案 0 :(得分:0)

我们可以使用嵌套循环

来完成此操作
for(i in WkD ){
  for(j in Wk) {
     MILKORDERS[paste(i, j, sep="_")] <- as.integer(MILKORDERS$WeekDay == i &
                       MILKORDERS$Week == j)
       }
 }

数据

set.seed(24)
MILKORDERS <- data.frame(WeekDay = sample(c("Wednesday",
    "Thursday", "Friday", "Saturday", "Sunday", "Tuesday", "Monday"),
          30, replace = TRUE), Week = sample(6, 30, replace=TRUE), 
         stringsAsFactors = FALSE)
WkD <- unique(MILKORDERS$WeekDay)
Wk <- unique(MILKORDERS$Week)