[R] howto create a list row-by-row as input to function call?

Mark Knecht markknecht at gmail.com
Thu Jul 23 20:04:03 CEST 2009


Hi,
   I'm having trouble within my function CalcPos to get it to call
CalcHorz with values from each row. I *think* it's calling CalcHorz
with the final values of the inputs and not the values from each row.
How can I do this properly in R?

   The values aa,bb,cc,dd are inputs. CalcPos first calculates V1 and
V2 vertically, and then I attempt to call CalcHorz to handle H1, H2 &
H3 using a list L1 comprised of df[aa:V2]. I wanted that list to be
the values on that row and disposed of each pass, but I think all
calls are probably using the final values. Finally I use the returned
values H1:H3 for more vertical calculations in V3.

   How can I get list L1 to be the unique row values for each call to
CalcHorz? L1 would just be tossed when the call to CalcPos is
complete.

   PLEASE - do not combine any of the inputs or return values. I need
all of them aa through V3 and want to keep them separate. Thanks!

Cheers,
Mark


CalcHorz = function (L1) {
	# Intended to calculate 3 values for each row
	H1 <- with(L1, V1*cc)
	H2 <- with(L1, V2*dd)
	H3 <- with(L1, H1 - H2)
	return(as.list(H1, H2, H3))
}

CalcPos = function (df) {

	#calculate vertical initially
	df$V1 <- with(df, aa*bb)
	df$V2 <- with(df, aa*cc-dd)

	#At this point do 3 horizontal calculations
	#Goal is this is done for each row using
	#the values aa,bb,cc,dd,V1,V2 for that row

	L1 = as.list(df[1:dim(df)[2]])

	R1 = as.list(with(df, CalcHorz(L1)))
	df$H1 <- R1[1]
	df$H2 <- R1[2]
	df$H3 <- R1[3]

	#Switch back to vertical

	df$V3 = with (df, cumsum(H3))

	return(df)
}


DF <- data.frame(aa=1:12, bb=12:15, cc=1:3, dd=1:6)
DF

DF <- CalcPos(DF)
DF




More information about the R-help mailing list