R: Use function to define variables inside data-set -
i want see how model performs when make variable 'year' piecewise linear. know there automatic methods define within model , best cut-point. still, prefer making piecewise variable more transparant me , in addition, think solution problem can on other occasions well.
so want make variables defined like
year1997up<-0 year1997up[year>1997]<-year[year>1997]-1997 year1997up[year<=1997]<-rep(0,sum(year<=1997)) year1997down<-0 year1997down[year<1997]<-year[year<1997]-1995 year1997down[year>=1997]<-rep(2,sum(year>=1997))
so year piecewise divided cut-point 1997.
i want years 1997 till 2011 , automate process, wrote function:
piece.var.fun<-function(up,down,i,data){ within(data,{ up<-0 up[year>=i]<-year[year>=i]-i up[year<i]<-rep(0,sum(year<i)) down<-0 down[year<=i]<-year[year<=i]-1995 down[year>i]<-rep(i-1995,sum(year>i)) }) } test.dataset<-piece.var.fun(up="year2000up",down="year2000down",data=startm,i=2000)
the idea use function in combination mapply on vectors containing names want, variables called , down instead of year2000up , year2000down. way, can't use make variables different years, named same.
so, how can use function , make name of variables include the year?
use assign
:
yr <- 1995 varname <- sprintf('year%idown', yr) down <- # ... define `down` before assign(varname, down)
you can create up
little easier, like
up <- cumsum(year > i)
aside: down
doesn't make sense me - why hard-coded 1995? , why stick '2' on end? imagine might able construct up
depending on want.
another aside: also, if construct up
, down
inside piece.var.fun
using i
already, there no need pass in variable name "year2000up" , on function? anyway, peripheral question.
but in case, answer question, include year in variable name create string variable name , use assign
.
Comments
Post a Comment