Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>EDIT: Fixed. I originally assumed that I would have to modify most of rle(), but it turns out only a few tweaks were needed.</p> <p>This isn't an answer about an *apply method, but I wonder if this might not be a faster approach to the process overall. As Shane says, loops aren't so bad. And... I rarely get to show my code to anyone, so I'd be happy to hear some critique of this.</p> <pre><code>#Shane, I told you this was awesome dat &lt;- getSOTable("http://stackoverflow.com/questions/1504832/help-me-replace-a-for-loop-with-an-apply-function", 1) colnames(dat) &lt;- c("day", "user_id") #Convert to dates so that arithmetic works properly on them dat$day &lt;- as.Date(dat$day) #Custom rle for dates rle.date &lt;- function (x) { #Accept only dates if (class(x) != "Date") stop("'x' must be an object of class \"Date\"") n &lt;- length(x) if (n == 0L) return(list(lengths = integer(0L), values = x)) #Dates need to be sorted x.sort &lt;- sort(x) #y is a vector indicating at which indices the date is not consecutive with its predecessor y &lt;- x.sort[-1L] != (x.sort + 1)[-n] #i returns the indices of y that are TRUE, and appends the index of the last value i &lt;- c(which(y | is.na(y)), n) #diff tells you the distances in between TRUE/non-consecutive dates. max gets the largest of these. max(diff(c(0L, i))) } #Loop max.consec.use &lt;- matrix(nrow = length(unique(dat$user_id)), ncol = 1) rownames(max.consec.use) &lt;- unique(dat$user_id) for(i in 1:length(unique(dat$user_id))){ user &lt;- unique(dat$user_id)[i] uses &lt;- subset(dat, user_id %in% user) max.consec.use[paste(user), 1] &lt;- rle.date(uses$day) } max.consec.use </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload