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))
}