I have a dataframe in R with 3 columns (variables). One of them, called Region, is some kind nested. I try to reproduce a little part of it.
df <- data.frame (freq = c(70, 72, 74, 76, 78,
70, 72, 74, 76, 78,
70, 72, 74, 76, 78),
region = c('region.1','region.1','region.1','region.1', 'region.1',
'region.1.1','region.1.1','region.1.1', 'region.1.1', 'region.1.1',
'region.2','region.2', 'region.2', 'region.2', 'region.2'),
dBvalue = c(-30, -32, -42, -45, -47,
-33, -28, -22, -37, -35,
-36, -55, -43, -26, -49))
Now I want to add 3 new colums. The first with the count of the observations per region (so in this case will be 1...5, 1...5, etc), the second must contain a grouping value, ant the last should have the higher hierarchical level of aggregation of the Region column in this case the final df would be:
df <- data.frame (freq = c(70, 72, 74, 76, 78,
70, 72, 74, 76, 78,
70, 72, 74, 76, 78),
region = c('region.1','region.1','region.1','region.1', 'region.1',
'region.1.1','region.1.1','region.1.1', 'region.1.1', 'region.1.1',
'region.2','region.2', 'region.2', 'region.2', 'region.2'),
dBvalue = c(-30, -32, -42, -45, -47,
-33, -28, -22, -37, -35,
-36, -55, -43, -26, -49),
count = c(1,2,3,4,5,
1,2,3,4,5,
1,2,3,4,5),
group = c(1,1,1,1,1,
2,2,2,2,2,
3,3,3,3,3),
higher_region = c("region.1","region.1","region.1","region.1","region.1",
"region.1","region.1","region.1","region.1","region.1",
"region.2","region.2","region.2","region.2","region.2"))
I'm trying with loop functions but i'm going crazy. Someone has a solution? Maybe using alternative methods?