How to loop over part of a character strong and make a new column

I need to make dummies for all weaks from 2000-2020 and think of using a for loop. My data looks like this

df <- data.frame( Time = c("2000W01","2000W02", "2000W03", "2000W04"
                    ,"2001W01","2001W02", "2001W03", "2001W04",
                    "2002W01","2002W02", "2002W03", "2002W04"),
                   Total = c(rep(3,12)))

df
    Time Total
1  2000W01     3
2  2000W02     3
3  2000W03     3
4  2000W04     3
5  2001W01     3
6  2001W02     3
7  2001W03     3
8  2001W04     3
9  2002W01     3
10 2002W02     3
11 2002W03     3
12 2002W04     3

I want to make a dummy variable (0 or 1) depending on which week of the year it is

    df <- data.frame( Time = c("2000W01","2000W02", "2000W03", "2000W04"
                        ,"2001W01","2001W02", "2001W03", "2001W04",
                        "2002W01","2002W02", "2002W03", "2002W04"),
                       Total = c(rep(3,12)),
             spring = c(1,0,0,0,1,0,0,0,1,0,0,0),
             summer = c(0,1,0,0,0,1,0,0,0,1,0,0),
             autumn = c(0,0,1,0,0,0,1,0,0,0,1,0),
             winter = c(0,0,0,1,0,0,0,1,0,0,0,1))




       Time Total spring summer autumn winter
1  2000W01     3      1      0      0      0
2  2000W02     3      0      1      0      0
3  2000W03     3      0      0      1      0
4  2000W04     3      0      0      0      1
5  2001W01     3      1      0      0      0
6  2001W02     3      0      1      0      0
7  2001W03     3      0      0      1      0
8  2001W04     3      0      0      0      1
9  2002W01     3      1      0      0      0
10 2002W02     3      0      1      0      0
11 2002W03     3      0      0      1      0
12 2002W04     3      0      0      0      1

How can I do this for a large dataset?



Read more here: https://stackoverflow.com/questions/67383933/how-to-loop-over-part-of-a-character-strong-and-make-a-new-column

Content Attribution

This content was originally published by Emil Krabbe at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: