1

I wish to add 106 new columns to my existing dataset using a for loop. I also wish to fill those columns with zeros and ones if the corresponding ID matches the new column like so:

Existing data:

df <- data.frame( geo = c("AL","AL", "AL", "BE","BE","BE","UK","UK","UK","FR","FR","FR"), Time = c(1,2,3,1,2,3,1,2,3,1,2,3))

df
    geo Time
1  AL    1
2  AL    2
3  AL    3
4  BE    1
5  BE    2
6  BE    3
7  UK    1
8  UK    2
9  UK    3
10 FR    1
11 FR    2
12 FR    3

What I want to make using a for loop or other command:

df1 <- data.frame( geo = c("AL","AL", "AL", "BE","BE","BE","UK","UK","UK","FR","FR","FR"),

         Time = c(1,2,3,1,2,3,1,2,3,1,2,3),
         AL = c(1,1,1,0,0,0,0,0,0,0,0,0),
         BE = c(0,0,0,1,1,1,0,0,0,0,0,0),
         UK = c(0,0,0,0,0,0,1,1,1,0,0,0),
         FR = c(0,0,0,0,0,0,0,0,0,1,1,1))

df1

  geo Time AL BE UK FR
1  AL    1  1  0  0  0
2  AL    2  1  0  0  0
3  AL    3  1  0  0  0
4  BE    1  0  1  0  0
5  BE    2  0  1  0  0
6  BE    3  0  1  0  0
7  UK    1  0  0  1  0
8  UK    2  0  0  1  0
9  UK    3  0  0  1  0
10 FR    1  0  0  0  1
11 FR    2  0  0  0  1
12 FR    3  0  0  0  1

My only problem is that the i does not work when I use the dollar sign "$" to loop over. I tried using `i' around the i but it still did not work.

My approach was to make a simple loop using the "$" but even reading other posts on stackoverflow did not solve my issue.

geo <- unique(df$geo)
   for (i in geo) {
     df$i<- vector(,nrow(df))

}
  • 1
    Try: `df[i] <- +(df$geo == i)` – GKi May 04 '21 at 09:59
  • 2
    You can also do it without a for loop: `cbind(df, model.matrix( ~ geo-1 , df))`. – s_baldur May 04 '21 at 10:08
  • What if I have a Time index with values for all weeks in the format 2000W01, 2000W02 all the way to 2020W52, is there a way to add dummies for summer if weeks are between W24 and W34 ? Again I need to use a loop "i" within a character string like 2000Wi – Emil Krabbe May 04 '21 at 10:56

0 Answers0