简体   繁体   中英

How do I sort one vector based on values of another (with data.frame)

I have a data frame 'true set', that I would like to sort based on the order of values in vectors 'order'.

true_set <- data.frame(dose1=c(rep(1,5),rep(2,5),rep(3,5)), dose2=c(rep(1:5,3)),toxicity=c(0.05,0.1,0.15,0.3,0.45,0.1,0.15,0.3,0.45,0.55,0.15,0.3,0.45,0.55,0.6),efficacy=c(0.2,0.3,0.4,0.5,0.6,0.4,0.5,0.6,0.7,0.8,0.5,0.6,0.7,0.8,0.9),d=c(1:15))

orders<-matrix(nrow=3,ncol=15)
orders[1,]<-c(1,2,6,3,7,11,4,8,12,5,9,13,10,14,15)
orders[2,]<-c(1,6,2,3,7,11,12,8,4,5,9,13,14,10,15)
orders[3,]<-c(1,6,2,11,7,3,12,8,4,13,9,5,14,10,15)

The expected result would be:

First orders[1,] :

   dose1 dose2 toxicity efficacy  d
1      1     1     0.05      0.2  1
2      1     2     0.10      0.3  2
3      2     1     0.10      0.4  6
4      1     3     0.15      0.4  3
5      2     2     0.15      0.5  7
6      3     1     0.15      0.5 11
7      1     4     0.30      0.5  4
8      2     3     0.30      0.6  8
9      3     2     0.30      0.6 12
10     1     5     0.45      0.6  5
11     2     4     0.45      0.7  9
12     3     3     0.45      0.7 13
13     2     5     0.55      0.8 10
14     3     4     0.55      0.8 14
15     3     5     0.60      0.9 15

First orders[2,] : as above

First orders[3,] : as above

true_set <- data.frame(dose1=c(rep(1,5),rep(2,5),rep(3,5)),     dose2=c(rep(1:5,3)),toxicity=c(0.05,0.1,0.15,0.3,0.45,0.1,0.15,0.3,0.45,0.55,0.15,0.3,0.45,0.55,0.6),efficacy=c(0.2,0.3,0.4,0.5,0.6,0.4,0.5,0.6,0.7,0.8,0.5,0.6,0.7,0.8,0.9),d=c(1:15))

orders<-matrix(nrow=3,ncol=15)
orders[1,]<-c(1,2,6,3,7,11,4,8,12,5,9,13,10,14,15)
orders[2,]<-c(1,6,2,3,7,11,12,8,4,5,9,13,14,10,15)
orders[3,]<-c(1,6,2,11,7,3,12,8,4,13,9,5,14,10,15)

# Specify your order set in the row dimension 
First_order <- true_set[orders[1,],]
Second_order <- true_Set[orders[2,],]
Third_order <- true_Set[orders[3,],]

# If you want to store all orders in a list, you can try the command below:

First_orders <- list(First_Order=true_set[orders[1,],],Second_Order=true_set[orders[2,],],Third_Order=true_set[orders[3,],])
First_orders[1]    # OR  First_orders$First_Order
First_orders[2]    # OR  First_orders$Second_Order
First_orders[3]    # OR  First_orders$Third_Order

# If you want to combine the orders column wise, try the command below:

First_orders <- cbind(First_Order=true_set[orders[1,],],Second_Order=true_set[orders[2,],],Third_Order=true_set[orders[3,],])

# If you want to combine the orders row wise, try the command below:

First_orders <- rbind(First_Order=true_set[orders[1,],],Second_Order=true_set[orders[2,],],Third_Order=true_set[orders[3,],])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM