在R中排序多个列

在R中排序多个列,r,R,样本数据: now <- data.frame(id=c(123,123,123,222,222,222,135,135,135),year=c(2002,2001,2003,2006,2007,2005,2001,2002,2003),freq=c(3,1,2,2,3,1,3,1,2)) 请注意,我需要快速高效的解决方案,因为我有长度为300K和50列的数据帧。谢谢 您可以使用dplyr对其进行排序,这在dplyr中称为arrange。dplyr也比plyr快 您可以对base R执行

样本数据:

now <- data.frame(id=c(123,123,123,222,222,222,135,135,135),year=c(2002,2001,2003,2006,2007,2005,2001,2002,2003),freq=c(3,1,2,2,3,1,3,1,2))
请注意,我需要快速高效的解决方案,因为我有长度为300K和50列的数据帧。谢谢

您可以使用dplyr对其进行排序,这在dplyr中称为arrange。dplyr也比plyr快

您可以对base R执行相同的操作:

wanted <- now[order(now$id, now$year),]

但是,您的now和wanted data.frame在id==123和year 2002的now df中存在差异,freq在wanted df中为2,而在wanted df中为3。根据您的问题,我假设这是一个输入错误,您实际上不想更改频率值。

您可以在这里使用base R函数

now <- now[order(now$id, now$year), ]


我已经试过base R和order。谢谢你的教训+1now[do.call'order',as.listnow[,-2],]
wanted <- now %>% arrange(id, year) 
# or: wanted <- arrange(now, id, year)

> wanted
#   id year freq
#1 123 2001    1
#2 123 2002    3
#3 123 2003    2
#4 135 2001    3
#5 135 2002    1
#6 135 2003    2
#7 222 2005    1
#8 222 2006    2
#9 222 2007    3
wanted <- now[order(now$id, now$year),]
now <- now[order(now$id, now$year), ]
library(data.table)
setDT(now)[order(id, year)]
now <- data.table(now, key = c("id", "year"))
setDT(now)
setkey(now, id, year)