R Panel数据根据字符变量重新排序行

时间:2014-08-19 10:30:13

标签: r string

我的数据类似于:

VarA    VarB    VarC
1   Paris   9
2   Paris   8
3   Paris   5
1   Boston  8
2   Boston  4
3   Boston  5
1   Miami   6
2   Miami   4
3   Miami   5
1   Dallas  8
2   Dallas  3
3   Dallas  7

我需要按照VarB(非字母)值的任意顺序以及VarA的顺序来命令VarC。它应该看起来像:

VarA    VarB    VarC
1   Miami   6
2   Miami   4
3   Miami   5
1   Paris   9
2   Paris   8
3   Paris   5
1   Dallas  8
2   Dallas  3
3   Dallas  7
1   Boston  8
2   Boston  4
3   Boston  5

目标订单:

target <- c("Miami", "Paris","Dallas","Boston")

我尝试过:

df[match(target,df$VarB),] 

以及

test1 <- df[rownames(target),,drop=FALSE]

test2 <- df[order(target),]

match功能无效,因为它是面板数据,而且有几个&#34; Miami&#34;和&#34;巴黎&#34;当重复变量B值时,它似乎会崩溃。

任何人都知道我做错了什么?

2 个答案:

答案 0 :(得分:4)

dat$VarB <- factor(dat$VarB, levels=target)
dat[order(dat$VarB, dat$VarA),]
#       VarA   VarB VarC
#7     1  Miami    6
#8     2  Miami    4
#9     3  Miami    5
#1     1  Paris    9
#2     2  Paris    8
#3     3  Paris    5
#10    1 Dallas    8
#11    2 Dallas    3
#12    3 Dallas    7
#4     1 Boston    8
#5     2 Boston    4
#6     3 Boston    5

答案 1 :(得分:3)

为什么不做“&#34; VarB&#34;有序因素?

factor(mydf$VarB, target, ordered = TRUE)
#  [1] Paris  Paris  Paris  Boston Boston Boston Miami  Miami  Miami 
# [10] Dallas Dallas Dallas
# Levels: Miami < Paris < Dallas < Boston
order(factor(mydf$VarB, target, ordered = TRUE))
#  [1]  7  8  9  1  2  3 10 11 12  4  5  6
mydf[order(factor(mydf$VarB, target, ordered = TRUE)), ]
#    VarA   VarB VarC
# 7     1  Miami    6
# 8     2  Miami    4
# 9     3  Miami    5
# 1     1  Paris    9
# 2     2  Paris    8
# 3     3  Paris    5
# 10    1 Dallas    8
# 11    2 Dallas    3
# 12    3 Dallas    7
# 4     1 Boston    8
# 5     2 Boston    4
# 6     3 Boston    5

在那里添加mydf$VarA以便按顺序排列。