I'm trying to build on Jim's approach to change the parameters in the function, with new rules:
1. if (x[i]==0) NA 2. if (x[i]>0) log(x[i]/(number of consecutive zeros preceding it +1)) x<-c(1,0,1,0,0,1,0,0,0,1,0,0,0,0,1) # i.e. output desired = c(0, NA, -0.69, NA, NA, -1.098, NA, NA, NA, -1.38, NA, NA, NA, NA, -1.61) y <- rle(x) # attempting to modify Jim's function: result <- lapply(seq_along(y$lengths), function(.indx){ if (y$values[.indx-1] == 0) log(y$values[.indx]/seq(y$lengths[.indx-1]+1, by=-1, length=y$lengths[.indx])) else rep(log(y$values[.indx]), y$lengths[.indx]) }) # but I am clearly missing something! Does it not work because I haven't addressed what to do with the zeros and log(0)=-Inf? I've tried adding another "ifelse" but I still get the same result. Can someone find the error in my ways? Tyler T.D.Rudolph wrote: > > > I have a matrix of frequency counts from 0-160. > x<-as.matrix(c(0,1,0,0,1,0,0,0,1,0,0,0,0,1)) > > I would like to apply a function creating a new column (x[,2])containing > values equal to: > a) log(x[m,1]) if x[m,1] > 0; and > b) for all x[m,1]= 0, log(next x[m,1] > 0 / count of preceding zero values > +1) > > for example, x[1,2] should equal log(x[2,1]/2) = log(1/2) = -0.6931472 > whereas x[3,2] should equal log(x[5,1]/3) = log (1/3) = -1.098612 > > I will be applying this to nrow(x)=~70,000 so I would prefer to not do it > by hand! > Tyler > > > > -- View this message in context: http://www.nabble.com/help-with-simple-function-tp17498394p17551527.html Sent from the R help mailing list archive at Nabble.com. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.