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

后端 未结 2 1539
感动是毒
感动是毒 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)
    } 
    

提交回复
热议问题