문제

I have 36 files where each file contains data for one month for a certain year, so in total I have 36/12=3 years. Files from 1 to 12 are for year 2013, 13 to 24 for year 2012, and 25 to 36 for year 2011. I am trying to create a function that will take a year or years as an argument and return corresponding interval of file numbers. My attempt:

g<-function(year){
 lis<-vector()
 for( i in year){
  if(year==2013){lis<-append(lis,1:12)}
  if(year==2012){lis<-append(lis,13:24)}
  if(year==2011){lis<-append(lis,24:36)}
 }
return(lis)
}

With single years my function works fine. For example:

> g(2013)
[1]  1  2  3  4  5  6  7  8  9 10 11 12

I want the following output when I call g(2013:2012) or g(2012:2013):

[1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

I thought if statements would do the trick, but it does not work. Let me know if you need any clarification. Thanks for your help.

도움이 되었습니까?

해결책

In your for loop, you don't actually use the individual values that you're looping through, you compare against the whole year vector every time. Using the individual values fixes your immediate problem:

g<-function(year){
  lis<-vector()
  for( i in year){
    if(i == 2013){lis<-append(lis,1:12)}
    if(i == 2012){lis<-append(lis,13:24)}
    if(i == 2011){lis<-append(lis,24:36)}
  }
  return(lis)
}

Or you could do the same thing without a for loop:

g2 <-function(year){
  lis<-vector()
  if (2013 %in% year) {lis <- append(lis, 1:12)}
  if (2012 %in% year) {lis <- append(lis, 13:24)}
  if (2011 %in% year) {lis <- append(lis, 24:36)}
  return(lis)
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top