[R] writing function : can't find an object
arnaud Gaboury
arnaud.gaboury at gmail.com
Wed May 26 09:17:34 CEST 2010
Dear group,
Here is my function:
#return the daily PL for day y
PLDaily<-function(x,y)
{
#find elements in my directory with "LSCPos" in the name, keep the numeric
part in the name and
#create a list
l<-gsub("\\D","",dir()[grep("LSCPos",dir())])
#select in the list the desired elements
assign("sel",l[which(l==x):which(l==y)],envir=.GlobalEnv)
#here is another solution select<-l[l %in% seq(x, y)]
#first we need to create the Pos and Trad elements
for (i in sel) {
assign(paste("Pos",i,sep=""),position(i),envir=.GlobalEnv)
assign(paste("Trad",i,sep=""),trade(i),envir=.GlobalEnv)
}
#access elements in my environment
posA<-get(paste(c("Pos",x),collapse=""))
posB<-get(paste(c("Pos",y),collapse=""))
av<-get(paste(c("Trad",y),collapse=""))
#apply some change on element columns then create only one data frame with
the three elements
allcon<-ddply(rbind(av[,1:3],
transform(posA,prix=POSITION*SETTLEMENT,SETTLEMENT=NULL),
transform(posB, prix = -POSITION * SETTLEMENT, SETTLEMENT = NULL,
POSITION = POSITION * -1)),
"DESCRIPTION",summarise,pl=sum(prix),quantity=sum(POSITION))
#remove the date in $DESCRPTION and add a new column $SHORTDESCRIPTION
allcon$SHORTDESCRIPTION<-sub('
[a-z]{3}/[0-9]{2}','',allcon$DESCRIPTION,ignore.case=TRUE)
#read the contractvalue file
value<-read.csv2("contractvalue.csv",sep=",",h=T,strip.white=T)
#merge "value" with "allcon", change some columns, then merge with PosB,
replace NA by zero and assign the final result to element PL
zz<-merge(transform(merge(value,allcon,all.y=T),SHORTDESCRIPTION=NULL,
VALUE=NULL,PL=-VALUE*pl,quantity=NULL),PosB,all.x=T,sort=F)
zz[is.na(zz)]<-0
#PL<-zz[c(1,3,4)]
assign(paste("DailyPL",y,sep=""),zz[,c(1,3,4)],envir=.GlobalEnv)
}
Here is what I get :
> PLDaily(100524,100525)
Error in as.data.frame(y) : object 'PosB' not found
> ls()
[1] "PLDaily" "Pos100524" "Pos100525" "position" "sel"
"Trad100524" "Trad100525" "trade"
Why R can't find "PosB" ?
TY for your help.
More information about the R-help
mailing list