问题描述
我需要重新排序与下面的数据帧相似的数据帧.我需要伦敦首先出现在任何其他Var中,但是在以后进行矩阵代数运算时,保持var的顺序("pop,gdp,lifespec ...")非常重要.
I need to reorder a data frame similar to the one below. I need London to appear first in any different Var, but it is quite critical to keep the var order as it is ("pop, gdp,lifespec...) as I am doing matrix algebra afterwards.
City Var value
Chicago pop 0.08
London pop 0.24
Paris pop 0.75
Chicago gdp 0.55
London gdp 0.49
Paris gdp 0.23
Chicago lifespec 0.45
London lifespec 0.39
Paris lifespec 0.28
Chicago percjobs 0.12
London percjobs 0.13
Paris percjobs 0.01
所以我想要的输出如下:
So my desired output would be like the following:
City Var value
London pop 0.24
Chicago pop 0.08
Paris pop 0.75
London gdp 0.49
Chicago gdp 0.55
Paris gdp 0.23
London lifespec 0.39
Chicago lifespec 0.45
Paris lifespec 0.28
London percjobs 0.13
Chicago percjobs 0.12
Paris percjobs 0.01
我试图创建一个df$rank
,其值为1到伦敦,其他值为9.然后,我尝试使用sort()
,但是所有伦敦值都在顶部折叠.你有什么主意吗?
I tried to create a df$rank
with values of 1 to London and 9 else. Then I tried to use sort()
, but all London values collapse on the top. Do you have any idea?
推荐答案
在此处收集对该问题的评论以提供简单的两层式.
Harvesting the comments on the question here to provide a simple two-liner.
d <- read.table(text='City Var value
Chicago pop 0.08
London pop 0.24
Paris pop 0.75
Chicago gdp 0.55
London gdp 0.49
Paris gdp 0.23
Chicago lifespec 0.45
London lifespec 0.39
Paris lifespec 0.28
Chicago percjobs 0.12
London percjobs 0.13
Paris percjobs 0.01', header=T)
d$Var <- factor(d$Var, unique(d$Var))
d[order(d$Var, d$City != "London"), ]
# City Var value
# 2 London pop 0.24
# 1 Chicago pop 0.08
# 3 Paris pop 0.75
# 5 London gdp 0.49
# 4 Chicago gdp 0.55
# 6 Paris gdp 0.23
# 8 London lifespec 0.39
# 7 Chicago lifespec 0.45
# 9 Paris lifespec 0.28
# 11 London percjobs 0.13
# 10 Chicago percjobs 0.12
# 12 Paris percjobs 0.01
这篇关于根据字符串变量对行进行重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!