[R] Question about apply()

Peter Dalgaard P.Dalgaard at biostat.ku.dk
Wed Feb 11 13:47:50 CET 2009


Sergey Goriatchev wrote:
> Hello, everyone!
> 
> Assume you have this data:
> data <- structure(c(66.609375, 67.09375, 66.40625, 66.734375, 67.109375,
> 66.875, 66.09375, 65.921875, 66.546875, 66.140625, 66.140625,
> 65.65625, 65.875, 65.59375, 65.515625, 66.09375, 66.015625, 66.140625,
> 66.109375, 66.421875, 1702.7, 1647.7, 1649.4, 1639.9, 1696.4,
> 1710.9, 1690.2, 1677.9, 1694.4, 1713.9, 1713.9, 1705.4, 1708.4,
> 1692.9, 1689.6, 1647.7, 1654.5, 1651.3, 1645.7, 1602.4, 453.7,
> 447.8, 446.2, 446.5, 447, 446.8, 448.5, 447.8, 449.2, 449, 449,
> 453.7, 454.4, 453.4, 453.8, 452.2, 450.7, 450.6, 451.4, 447.5,
> 18.34, 18.29, 17.65, 17.52, 16.96, 17.41, 18.51, 19.02, 19.43,
> 20.76, 20.76, 21.59, 22.28, 22.4, 22.63, 22.26, 22.71, 22.27,
> 21.75, 21.65), .Dim = c(20L, 4L), .Dimnames = list(NULL, c("TY1.lev",
> "SP1.lev", "GC1.lev", "CL1.lev")), index = structure(c(10959,
> 10960, 10961, 10962, 10963, 10966, 10967, 10968, 10969, 10970,
> 10973, 10974, 10975, 10976, 10977, 10980, 10981, 10982, 10983,
> 10984), class = "Date"), class = "zoo")
> 
> What I want to do is to calculate simple return on each column (return=P1/P0-1)
> and put it in new columns.
> 
> I've tried like this:
> 
> #convenience function
> func <- function(x,z){
> 	a <- embed(x[z, drop=FALSE], 2)[,1]/embed(x[z, drop=FALSE], 2)[,2] - 1
> 	return(a)
> }
> 
> data <- merge(data, Bond.ret=zoo(apply(data, 2, func, z="TY1.lev"),
> order.by=time(data)[-1]))
> 
> and I get this:
> Error in embed(x[z, drop = FALSE], 2) : wrong embedding dimension
> 
> What am I doing wrong?
> (Somehow I cannot understand how to work with columns in apply(), with
> rows, that is apply(,1,FUN)  I have no problem.

The immediate problem is that you are missing a comma in x[, z, drop =
FALSE]. But what was wrong with

cbind(data,data/lag(data,-1)-1, suffixes=c("","r"))

(except that it adds a "." to the orginal names, I see no way of NOT
adding a suffix?)

-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark      Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)              FAX: (+45) 35327907




More information about the R-help mailing list