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

后端 未结 2 1518
感动是毒
感动是毒 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:13

    I think you mean this:

    vec1 <- sample(1:574)
    L = vec1[1:143]
    H = vec1[144:length(vec1)]
    

    Anyway by percentage you can do this:

    vec1 <- sample(1:574)
    num_to_25 <- floor(0.25*length(vec1))
    L = vec1[1:num_to_25]
    H = vec1[(num_to_25+1):length(vec1)]
    

    With function you can Use:

    assigner = function (input_vactor,percentage_of_L=25){
       num_to_25 <- floor(percentage_of_L*0.01*length(input_vactor))
       L = input_vactor[1:num_to_25]
       H = input_vactor[(num_to_25+1):length(input_vactor)]
       return (list(L=L,H=H))
    }
    

    And use it like this:

    vec1 <- sample(1:574)
    h = assigner(vec1)$H
    l = assigner(vec1)$L
    

    Edit for Edit: For your edited question change second function to this:

    sensitivity.rand <- function(vector, threshold){
      num_to_thres <- floor(threshold*0.01*length(vector))
      l = length (vector)
      score = c(rep("L",num_to_thres),rep("H",l-num_to_thres))
      return(score)
    } 
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题