[R] Split a data.frame

Rui Barradas ruipb@rr@d@@ @ending from @@po@pt
Sat May 19 16:58:44 CEST 2018


Hello,

Maybe something like the following.

splitDF <- function(data, col, s){
     n <- nrow(data)
     inx <- which(data[[col]] %in% s)
     lapply(seq_along(inx), function(i){
         k <- if(inx[i] < n) (inx[i] + 1):(inx[i + 1])
         data[k, ]
     })
}

splitDF(DF, "name", split_str)


Hope this helps,

Rui Barradas

On 5/19/2018 12:07 PM, Christofer Bogaso wrote:
> Hi,
> 
> I am struggling to split a data.frame as will below scheme :
> 
> DF = data.frame(name = c('a', 'v', 'c'), val = 0); DF
> 
> split_str = c('a', 'c')
> 
> Now, for each element in split_str, R should find which row of DF contains
> that element, and return DF with all rows starting from next row of the
> corresponding element and ending with the preceding value of the next
> element.
> 
> So in my case, I should see 2 data.frames
> 
> 1st data-frame with name = 'v' (i.e. 2nd row of DF)
> 
> 2nd data.frame with number_of_rows as 0 (as there is no row left after 'c')
> 
> Similarly if split_str = c('v'') then, my 2 data.frames will be
> 
> 1st data.frame with name = 'a'
> 2nd data.frame with name = 'c'
> 
> Any idea how to efficiently implement above scheme would be highly
> appreciated. I tried with split() function, however, it is not giving the
> right answer.
> 
> Thanks,
> 
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.
>



More information about the R-help mailing list