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
它已经存在:'#...但我们希望像这样递增顺序的结果向量:1 2 3 4 5 4 6 6 7 7' – smci
'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
无论如何,墨菲定律说我把我的头撞了很久,然后我把它作为一个问题发布,我偶然发现了答案(下面)。 – smci