Suppose I have this dataframe:
df <- data.frame(town = c("town1","town2","town3"),
totpop = c(1700, 1500, 1200),
groupAreceived = c(10, 5, 2),
groupBreceived = c(9, 4, 1),
groupCreceived = c(8, 3, 0))
that looks like:
df
town totpop groupAreceived groupBreceived groupCreceived
1 town1 1700 10 9 8
2 town2 1500 5 4 3
3 town3 1200 2 1 0
I want to create a new dataframe with four columns that replicates the town, group, and amount received with the number of rows based on the total population.
I can do this manually for one town:
town1.a <- data.frame(matrix(ncol = 4, nrow = df$totpop[[1]]))
x <- c("totpop", "group", "received", "town")
colnames(town1.a) <- x
totpop <- c(rep(1, df$totpop[[1]]))
group <- c(rep("A", df$totpop[[1]]))
received <- c(rep(df$groupAreceived[[1]], df$totpop[[1]]))
town <- c(rep("Town1", df$totpop[[1]]))
town1.a$totpop <- totpop
town1.a$group <- group
town1.a$received <- received
town1.a$town <- town
head(town1.a)
totpop group received town
1 1 A 10 Town1
2 1 A 10 Town1
3 1 A 10 Town1
4 1 A 10 Town1
5 1 A 10 Town1
6 1 A 10 Town1
This dataframe will have 1700 rows.
How can I automate this code/ use it in a for loop so that it will do the same thing but for each group?
Thanks in advance.