2014-04-12 18 views
0

此问题是this question的后续行动。如何将任意整数向量重新排列为递增顺序

比方说,我有一个大的data.frame, df,列u, v。我希望以递增顺序对u, v的观察到的变量交互进行编号,即从上到下穿过data.frame时看到它们的顺序。

注意:假设df有一些现有的顺序,所以临时对其重新排序是不好的。

该帖子底部显示的代码运行良好,除了返回的结果向量不是递增顺序的。也就是说,而不是目前的:

# result is in decreasing order here: 
match(df$label, levels(df$label)) 
# [1] 5 6 3 7 4 7 2 2 1 1 

# but we'd like it to be in increasing order like this: 
# 1 2 3 4 5 4 6 6 7 7 

我一直在order(), rank(), factor(...ordered=T)等,并似乎没有任何工作试验。我必须忽略一些明显的东西。有任何想法吗?

注意:也不允许通过将u, v重新排序为单独因素来作弊。

set.seed(1234) 
df <- data.frame(u=sample.int(3,10,replace=T), v=sample.int(4,10,replace=T)) 
# u v 
# 1 1 3 
# 2 2 3 
# 3 2 2 
# 4 2 4 
# 5 3 2 
# 6 2 4 
# 7 1 2 
# 8 1 2 
# 9 2 1 
# 10 2 1 

(df$label <- factor(interaction(df$u,df$v), ordered=T)) 
# [1] 1.3 2.3 2.2 2.4 3.2 2.4 1.2 1.2 2.1 2.1 
# Levels: 2.1 < 1.2 < 2.2 < 3.2 < 1.3 < 2.3 < 2.4 

# This is ok except want increasing-order 
match(df$label, levels(df$label)) 
# [1] 5 6 3 7 4 7 2 2 1 1 

# no better.  
match(df$label, levels(df$label)[rank(levels(df$label))]) 
# [1] 6 7 1 4 3 4 5 5 2 2 
+0

它已经存在:'#...但我们希望像这样递增顺序的结果向量:1 2 3 4 5 4 6 6 7 7' – smci

+0

'interaction'的输出因子级别的编号是任意的。不要把它称为'1 2 3 4 5 4 6 6 7 7',而应该认为它是E,F,C,G,D,G,B,B,A,A。唯一重要的是首先看到E(=> 1),F是第二个(=> 2)等等。所以我们的df $ label的矢量只需要重新编号(不知何故)为1 2 3 4 5 4 6 6 7 7。我希望我清楚:S – smci

+0

无论如何,墨菲定律说我把我的头撞了很久,然后我把它作为一个问题发布,我偶然发现了答案(下面)。 – smci

回答

0

呃!解决方案是添加interaction(... drop=T)。我仍然不完全明白为什么没有这样做会破坏事情。

# The original factor from interaction() had unused levels... 
str(df$label) 
# Factor w/ 12 levels "1.1","1.2","1.3",..: 3 7 6 8 10 8 2 2 5 5 

# SOLUTION 
df$label <- interaction(df$u,df$v, drop=T) 

str(df$label) 
# Factor w/ 7 levels "2.1","1.2","2.2",..: 5 6 3 7 4 7 2 2 1 1 

rank(unique(df$label)) 
# [1] 5 6 3 7 4 2 1 

我们将使用该等级(如上图所示)来重新调整水平阶观察,如下对他们我们的矢量匹配之前:

# And now we get the desired result 
match(df$label, levels(df$label)[ rank(unique(df$label)) ]) 
# [1] 1 2 3 4 5 4 6 6 7 7