Randomly associate elements of two vectors given conditions

前端 未结 5 766
心在旅途
心在旅途 2021-01-23 18:26

I have a data.table of capitals

capitals<-data.table(capital=c(100,50,25,5))
capitals
   capital
1:     100
2:      50
3:      25
4:       5
         


        
5条回答
  •  春和景丽
    2021-01-23 18:57

    For an easily understandable answer: You can first build a column loss in capitals data.frame and then repeatedly sample for those rows which needs to be corrected:

    capitals<-data.frame(capital=c(100,50,25,5))
    loss=c(45,10,5,1)
    
    capitals$loss <- sample(loss,replace=F)
    capitals
       capital loss
    1     100    5
    2      50   10
    3      25    1
    4       5   45
    
    for(i in 1:nrow(capitals)) {
        while(capitals[i,2]>capitals[i,1]){
            capitals[i,2] <- sample(loss, 1)
        }
    }
    
    capitals
    capital loss
    1     100    5
    2      50   10
    3      25    1
    4       5    5
    

    (Note that the last row has been corrected)

    If replace=F is needed, one can repeat sampling of entire dataframe till all rows satisfy the criteria:

        capitals<-data.frame(capital=c(100,50,25,5))
        loss=c(45,10,5,1)
    
        capitals$loss <- sample(loss,replace=F)
        capitals
           capital loss
        1     100    5
        2      50   10
        3      25    1
        4       5   45
    
    while (any(capitals$loss > capitals$capital)) { 
                    capitals$loss <- sample(loss,replace=F)}
    
    capitals 
      capital loss
    1     100   10
    2      50   45
    3      25    5
    4       5    1
    

提交回复
热议问题