gpt4 book ai didi

在数据框中以数字方式对因子进行重新排序

转载 作者:行者123 更新时间:2023-12-04 10:08:19 25 4
gpt4 key购买 nike

我有从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] "6" "7" "8" "9"

如何出于显示目的按数字顺序对其重新排序?我不想更改数据框的含义。

更新:如何使用排序后的因子 items更新原始数据帧 labels?这不应实质性地更改数据帧;我只希望这些因素在后续操作中以正确的顺序出现。

最佳答案

sorted_labels <- paste(sort(as.integer(levels(items$label))))

给出:
 [1] "0"  "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11"
[13] "12" "13" "14" "15" "16" "17" "18" "19" "20" "21" "22" "23"
[25] "24" "25" "26" "27" "28" "29" "30" "31" "32" "33" "34" "35"
[37] "36" "37" "38" "39"

或者(如 https://stackoverflow.com/a/15665655/109618中所述):
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)

关于在数据框中以数字方式对因子进行重新排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15665535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com