r - looping rep function with unequal groups -



r - looping rep function with unequal groups -

first time poster on site frequent visitor.

i have dataset containing 50 individual animals. each animal has 400-700 locations. i'm attempting separate 8 consecutive steps per individual (e.g., steps 1-8, 9-16, 17-24, , on) analysis. i'm trying add together new column dataframe identifies groups of steps individuals (steps 1-8 1, steps 9-16, 2...) merged animal id.

i'm attempting loop replicate function information. this:

for (i in unique (pathdf$id)){ n<-rep(1:700,each=8,length.out=348644) pathdf$newcolumn[i]<-n }

unfortunately, individual groups not have row numbers equal 8. i've tried different approaches remedy issue no avail. help appreciated.

it not clear whether steps created after ordering based on locations within each id. if case, first dataset ordered , create steps using ave

pathdf1 <- pathdf[with(pathdf, order(id, locations)),] row.names(pathdf1) <- null pathdf1 <- within(pathdf1, steps <- ave(id, id, fun=function(x) (seq_along(x)-1)%/%8 +1))

or using dplyr

library(dplyr) pathdf2 <- pathdf1 %>% group_by(id) %>% mutate(steps1 =rep(1:ceiling(n()/8), each=8, length.out=n())) all.equal(pathdf2$steps, pathdf2$steps1) #[1] true data set.seed(49) pathdf <- data.frame(id=sample(1:20,20*40,replace=true), locations=sample(20*40))

r

Comments

Popular posts from this blog

c - Compilation of a code: unkown type name string -

java - Bypassing "final local variable defined in an enclosing type" -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -