[R] How to access objects outside an R function
Jim Lemon
bitwrit at ozemail.com.au
Sat Feb 9 12:36:54 CET 2002
anantha rao wrote:
> ...I have a dataframe ('forexdata') of daily returns from the foreign exchange market for three currencies - British Pound (bp), Canadian
> Dollar(cd),
> Deustche Mark (dm) vis-a-vis the US Dollar and the Date Of
> Trade(yymmdd).
>
> For some dates the returns are missing (recorded as zero) as there
> were no trades in that currency for that date. My task is to
> substitute the missing or zero values with the next non-zero value.
Here is a function that will replace the zeros with the _last_ non-zero value (which is what you did in your solution). Note that it will produce
NAs if the _first_ value in a column is zero. Supply the data frame and a vector of column indices (in your case 3:5) to which you want to apply the
function. Hope this helps.
Jim
sub.last.value<-function(x.df,cols=1:dim(x.df)[2]) {
nrows<-dim(x.df)[1]
newcol<-vector("numeric",nrows)
for(col in 1:length(cols)) {
last.value<-NA
for(row in 1:nrows) {
if(x.df[row,cols[col]] > 0)
newcol[row]<-last.value<-x.df[row,cols[col]]
else newcol[row]<-last.value
}
x.df[cols[col]]<-newcol
}
return(x.df)
}
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list