通过两列重新排列数据帧

时间:2017-06-13 16:38:36

标签: r dataframe

如何通过降低列$vehicle = Vehicle::with('customer')->find($id); 中值的顺序来排列数据框,其中value列中的值

离。数据框

"cat"=X

离。重新排列数据框(我想看):

enter image description here

我在this article上查看第一个答案后尝试了df1<-data.frame(group=rep(c("A", "B", "C", "D"),each=2), cat=rep(c("X", "Y"),4), value=c(1,0.6,1,0.5,1,2,1,5)) ,但它没有用,结果如下:

enter image description here

正如您所看到的,这两个表看起来不同。我也尝试从df1[with(df1, order(-value, cat)),]包中安排命令,但每个结果都与上面的结果类似。

谢谢

1 个答案:

答案 0 :(得分:1)

由于value的{​​{1}}始终相同,我们可以将cat'x'value相加,然后使用它来对数据进行排序。

group

或另一种(可能更好的)方式涉及指定因子水平。它们默认按字母顺序设置,但您可以根据# Create data.frame df1<-data.frame(group=rep(c("A", "B", "C", "D"),each=2), cat=rep(c("X", "Y"),4), value=c(1,0.6,1,0.5,1,2,1,5)) # Sum values by group (since x is same...) df2 <- aggregate(df1$value, by=list(group=df1$group), FUN=sum) # Join tables library(plyr) output <- join(df1, df2, by='group', type='left', match='all') # Sort output <- output[with(output, order(-x, cat)),]

的顺序设置它们
value
相关问题