conditionally assign first nth element in vector as H and rests as L

后端 未结 2 1550
感动是毒
感动是毒 2021-01-23 08:50

I have a vector of randomly sampled numbers. For example,

vec1 <- sample(1:574)

I would like to assign first 25 percent value in this sample

2条回答
  •  半阙折子戏
    2021-01-23 09:16

    caretpackage includes createDataPartition function, that will do the job:

    library("caret")
    
    SAMPLE_SIZE <- 0.25
    SIZE_VECT <- 574
    
    # Set seed for reproducibility
    set.seed(pi)
    
    vec1 <- sample(1:SIZE_VECT)
    
    in_sample <- createDataPartition(y = vec1, p = SAMPLE_SIZE, list = FALSE)
    H <- vec1[in_sample]
    L <- vec1[-in_sample]
    # Actual sample size
    100 * length(H) / (length(L) + length(H))
    #  [1] 25.08711
    

提交回复
热议问题