重新排序数据列

时间:2017-05-10 18:25:52

标签: r dataframe

我尝试重新排序我的列,但无法弄清楚如何为我的列中的某个订单执行此操作。例如。我有以下data.frame

// Your counter
int counter = 0; 

// The contents of this will execute 100 times
for(gallons = 1; gallons <= 100; gallons++) { 

    // Omitted for brevity

    // This increases your counter by 1
    counter++; 

    // Since your counter is declared outside of the loop, it is accessible here
    // so check its value
    if(counter == 10) { 

         // If it is 10, then reset it
         System.out.println(); 
         counter = 0; 
    } 

    // At this point, the loop is over, so go to the next iteration
} 

所以我的目标是按名称和时间排序;但是时间必须按照target.time描述的顺序。

通过执行以下操作,我可以实现多列排序;

df <- data.frame(name=c("a","a","a","b","b","c","c","c","c"), time=c("screen","third","second","first","second","fourth","third","first","screen"), first_values=c("0.11", "0.23", "0.03", "0.4", "0.10", "0.25", "0.87","0.11","0.21"), second_values=c("0.05", "0.32", "0.63", "0.67", "0.10", "0.25", "0.87","0.11","0.91"))

target.time <- c("zeros", "screen", "first", "second", "third", "fourth")

但我不知道如何使用target.time订单订购时间,而df $ name对于相关行仍然是唯一的。

1 个答案:

答案 0 :(得分:4)

一种常见的方法是重新排序df$time的因子级别,然后使用order

# reassign factor levels according to target.time
df$time <- factor(df$time, levels=target.time)

# order data.frame
df[order(df$name, df$time),]
  name   time first_values second_values
1    a screen         0.11          0.05
3    a second         0.03          0.63
2    a  third         0.23          0.32
4    b  first          0.4          0.67
5    b second         0.10          0.10
9    c screen         0.21          0.91
8    c  first         0.11          0.11
7    c  third         0.87          0.87
6    c fourth         0.25          0.25