내용

글번호 676
작성자 heojk
작성일 2017-06-01 12:44:03
제목 sampleBy 함수에서 계통 추출시 처음 데이터부터 출력되는 단점을 제거한 함수
내용
#sampleBy 함수에서 계통 추출 시 첫 번째 항목부터 출력되는 단점을 수정한 함수
sampleBy2 <- function(formula, 
                      frac=0.1, 
                      replace=FALSE, 
                      data=parent.frame(),
                      systematic=FALSE)
{
  ddd<-splitBy(formula, data=data)
  
  ddd<- lapply(ddd, function(dat){
    if (systematic==TRUE){
      rand <- sample(1:floor(nrow(dat)*frac), 1)
      idx <- seq(rand,nrow(dat),1/frac)
    } else {  
      idx <- sort(sample(1:nrow(dat), size=round(frac*nrow(dat)), replace=replace))
    }
    dat[idx,]
  }) 
  ddd <-do.call("rbind",ddd)
  return(ddd)
}
sampleBy2(~Species, frac=0.1, data = iris, systematic = T)