Note that there are some explanatory texts on larger screens.

plurals
  1. POHelp me replace a for loop with an "apply" function
    primarykey
    data
    text
    <p>...if that is possible</p> <p>My task is to find the longest streak of continuous days a user participated in a game.</p> <p>Instead of writing an sql function, I chose to use the R's rle function, to get the longest streaks and then update my db table with the results.</p> <p>The (attached) dataframe is something like this:</p> <pre><code> day user_id 2008/11/01 2001 2008/11/01 2002 2008/11/01 2003 2008/11/01 2004 2008/11/01 2005 2008/11/02 2001 2008/11/02 2005 2008/11/03 2001 2008/11/03 2003 2008/11/03 2004 2008/11/03 2005 2008/11/04 2001 2008/11/04 2003 2008/11/04 2004 2008/11/04 2005 </code></pre> <p>I tried the following to get per user longest streak</p> <pre><code># turn it to a contingency table my_table &lt;- table(user_id, day) # get the streaks rle_table &lt;- apply(my_table,1,rle) # verify the longest streak of "1"s for user 2001 # as.vector(tapply(rle_table$'2001'$lengths, rle_table$'2001'$values, max)["1"]) # loop to get the results # initiate results matrix res&lt;-matrix(nrow=dim(my_table)[1], ncol=2) for (i in 1:dim(my_table)[1]) { string &lt;- paste("as.vector(tapply(rle_table$'", rownames(my_table)[i], "'$lengths, rle_table$'", rownames(my_table)[i], "'$values, max)['1'])", sep="") res[i,]&lt;-c(as.integer(rownames(my_table)[i]) , eval(parse(text=string))) } </code></pre> <p>Unfortunately this for loop takes too long and I' wondering if there is a way to produce the res matrix using a function from the "apply" family.</p> <p>Thank you in advance </p>
    singulars
    1. This table or related slice is empty.
    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.
 

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