-2

I have included a sample of my data In my R code I have a loop that goes trough the regions (ES00, ES11, ES12, so on) and for the years (2006, 2007, 2008, 2009, 2010). What I would like to do is to sum in ES00 (it is empty now)the addition of the others regions (ES00=ES11+ES12+ES13) per each year.

Thank you very much for your help in advance.

2 Answers2

0

I created a dummy dataset based on your's

data = data.frame(c("ES00","ES00","ES11","ES11","ES12","ES12"),c(2006,2007,2006,2007,2006,2007),c(0,0,12,13,14,15))
names(data) = c("Region","Year","amount")

so this looks like following:

data
  Region Year amount
1   ES00 2006      0
2   ES00 2007      0
3   ES11 2006     12
4   ES11 2007     13
5   ES12 2006     14
6   ES12 2007     15

You can use a loop for every year in your data base and do the following:

data$amount[(data$Year==2006) & data$Region=="ES00"] = sum(data$amount[(data$Year==2006)&(data$Region!="ES00")])

If you want to get a little bit more fancy you can use plyr library and since your metrics for region ES00 are 0 do the following:

ddply(data,.(Year),summarize, new_amount =sum(amount))

which will look something like this:

  Year new_amount
1 2006         26
2 2007         28
Diego Aguado
  • 1,604
  • 18
  • 36
0

Try this code (considering your dataframe name is 'data')

for (yr in 2006:2010){
for (i in 3:7){
data[data$Region=='ES00'& data$Year ==yr,i] = 
                sum(data[data$Region=='ES00' & data$Year==yr,i]
}
}
Vikram Venkat
  • 663
  • 4
  • 16
  • Thank you very much for your answer. The issue is that I have select a sample from a big data. The common thing is that all the regions have the same pattern XX00, then, could it be possible to write Region == to a certain pattern? – capercas Mar 08 '16 at 09:00
  • Yes using grepl #regular expressions matching in R – Vikram Venkat Mar 08 '16 at 10:32
  • for (yr in 2006:2010){ for (i in 3:16){ data[grepl("$00",data$Region),] & data$Year ==yr,i] = sum(data[data$Region==nuts & data$Year==yr,i]) } } – capercas Mar 08 '16 at 12:46
  • Sorry, I do not know how to put the code in a proper way to be read. What I try to tell with the code above is that I got an error in the grepl. I would like to write is if the patterncontains "00" or finish in "00". – capercas Mar 08 '16 at 12:59