vendredi 22 septembre 2017

R - create new column in data fame based on conditional

I need to create a column in a data frame with a string of yrs that will identify each yr as "leap" or "reg" (regular) automatically.

This is what I have this far:

Delimit the time period

year<-(2009:2017)

Create a data frame with a single column for that time period

prd_df<-data.frame(year)

Create an empty column where "leap" and "reg" yrs will be identified

prd_df["leap"]<-NA

Base identification with a conditional loop

for(i in 1:length(prd_df$year)){
  if((prd_df$year[i]%%4==0)&(prd_df$year[i]%%100!=0)){
    prd_df$leap<-'leap'
  }else if((prd_df$year[i]%%4==0)&(prd_df$year[i]%%100==0)&(prd_df$year[i]%%400==0)){
    prd_df$leap<-'leap' 
  }else{
    prd_df$leap<-'reg'
  }
}

Create a table from the resulting data frame.

write.table(prd_df,
          file = "prd.csv",
          row.names = F, col.names = T,
          sep = "\t")

This is what I get:

"year"  "leap"
2009    "reg"
2010    "reg"
2011    "reg"
2012    "reg"
2013    "reg"
2014    "reg"
2015    "reg"
2016    "reg"
2017    "reg"

In the example above, 2012 and 2016 should be identified as "leap" in the second column, but it is not working. The conditional has worked fine before as part of other codes but I can't get it to work now. It may not be recognizing prd_df$year as numeric?

Any suggestions will be most appreciated.

Thanks

Aucun commentaire:

Enregistrer un commentaire