R 在数据帧中以数字方式重新排列因子
我有从0到39的因子。以下是它们现在的订购方式:R 在数据帧中以数字方式重新排列因子,r,sorting,R,Sorting,我有从0到39的因子。以下是它们现在的订购方式: > levels(items$label) [1] "0" "1" "10" "11" "12" "13" "14" "15" "16" "17" "18" "19" [13] "2" "20" "21" "22" "23" "24" "25" "26" "27" "28" "29" "3" [25] "30" "31" "32" "33" "34" "35" "36" "37" "38" "39" "4" "5" [37]
> levels(items$label)
[1] "0" "1" "10" "11" "12" "13" "14" "15" "16" "17" "18" "19"
[13] "2" "20" "21" "22" "23" "24" "25" "26" "27" "28" "29" "3"
[25] "30" "31" "32" "33" "34" "35" "36" "37" "38" "39" "4" "5"
[37] "6" "7" "8" "9"
为了便于显示,如何按数字顺序对其重新排序?我不想改变数据帧的含义
更新:如何使用排序因子标签
更新原始数据框项
?这不应实质性地改变数据帧;我只想在后续的操作中以正确的顺序列出这些因素
sorted_labels <- paste(sort(as.integer(levels(items$label))))
或(如中所述):
sorted_标签如果所有整数都存在,那么您只需使用顺序
:
order(levels(items$label)) - 1 # where the minus 1 is for starting from 0
如果不是所有整数都存在,那么您必须使用as.numeric,就像您拥有它一样 如果您正在寻找适用于猫的tidyverse
/解决方案:
生成数据:
items[1]01 2 3 4 5 6 7 8 9 10 11 12 13 15 17 19 20 21 22
#> [24] 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
#>40级:01112141516171819202012223242526。。。9
使用fct_relevel
库(用于猫)
fct_relevel(items$label,函数(x){as.character(sort(as.integer(x)))})
#> [1] 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#> [24] 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
#>40级:01 2 3 4 5 6 7 8 9 10 11 13 14 15 16 17 18 19 20 21。。。39
它还适用于fct\u重新排序
fct_重新排序(items$label,as.integer(items$label))
#> [1] 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#> [24] 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
#>40级:01 2 3 4 5 6 7 8 9 10 11 13 14 15 16 17 18 19 20 21。。。39
如果向量还包含字符(例如,1个鸡蛋
,2个鸡蛋
等),那么这就提供了一些很好的可能性:
items$label2[1]0个蛋1个蛋2个蛋3个蛋4个蛋5个蛋6个蛋7个蛋
#>[9]8个蛋9个蛋10个蛋11个蛋12个蛋13个蛋14个蛋15个蛋
#>[17]16蛋17蛋18蛋19蛋20蛋21蛋22蛋23蛋
#>[25]24个蛋25个蛋26个蛋27个蛋28个蛋29个蛋30个蛋31个蛋
#>[33]32个蛋33个蛋34个蛋35个蛋36个蛋37个蛋38个蛋39个蛋
#>40级:0个蛋1个蛋10个蛋11个蛋12个蛋13个蛋。。。9个鸡蛋
图书馆(readr)
fct_重新排序(项目$label2,分析_编号(项目$label2))
#>[1]0个蛋1个蛋2个蛋3个蛋4个蛋5个蛋6个蛋7个蛋
#>[9]8个蛋9个蛋10个蛋11个蛋12个蛋13个蛋14个蛋15个蛋
#>[17]16蛋17蛋18蛋19蛋20蛋21蛋22蛋23蛋
#>[25]24个蛋25个蛋26个蛋27个蛋28个蛋29个蛋30个蛋31个蛋
#>[33]32个蛋33个蛋34个蛋35个蛋36个蛋37个蛋38个蛋39个蛋
#>40级:0蛋1蛋2蛋3蛋4蛋5蛋6蛋。。。39个鸡蛋
由(v0.3.0)于2019-06-26创建
fct_*函数的所有输出都可以写回原始数据。例如:
items$数据更简洁。根据我更新的问题,我如何用已排序的级别更新原始数据帧?@DavidJames这对我来说是另一个问题;)@DavidJames,您需要详细说明“更新”的含义您想要的最终结果是什么?items$label注意,order
从1开始重新索引:order(c(0,1,2))
给出123
。您使用的是paste()
而不是as.character()
?
sorted_labels <- order(levels(items$label)) - 1
# order by itself is a 1-based vector
# using `- 1` gives a 0-based vector
items$label <- factor(items$label, levels = sorted_labels)
order(levels(items$label)) - 1 # where the minus 1 is for starting from 0