gpt4 book ai didi

r - 根据频率更改 R 中数据帧的值

转载 作者:行者123 更新时间:2023-12-05 07:06:34 24 4
gpt4 key购买 nike

我正在尝试将 R 中数据框中的字符值重新编码为:

freq(prueba$frutas, sort = "dec")

n % val%
BANANA 36793 61.9 66.3
UVA 5206 8.8 9.4
FRESA 3153 5.3 5.7
CEREZA 2883 4.9 5.2
MANZANA 2748 4.6 4.9
MANGO 1680 2.8 3.0
MELON 1063 1.8 1.9
SANDIA 1061 1.8 1.9
OTROS 766 1.3 1.4
PERA 97 0.2 0.2
KIWI 72 0.1 0.1
BROCOLI 1 0.0 0.0
NA 3877 6.5 NA

所以我想将数据框中频率低于 6% 的所有“字符”值替换为“其他”,因此结果将是:

freq(prueba$frutas, sort = "dec")

n % val%
BANANA 36793 61.9 66.3
OTHER 13524 22.8 24.3
UVA 5206 8.8 9.4
NA 3877 6.5 NA

通常我使用 replace 来替换值,如下所示,但我想知道是否有更好的方法使用 6% 值来完成。

prueba$frutas <- replace(prueba$frutas, which(prueba$frutas != c("BANANA","UVAS")) , "OTHER")

最佳答案

如果没有您的数据和更多信息,我可以提供 forcats::fct_lump_prop。这是一个使用来自 questionr 的数据集的示例,我相信您是从中获取 freq 函数的。

library(questionr)
library(forcats)

data(hdv2003)
freq(hdv2003$qualif, sort = "dec")

#> n % val%
#> Employe 594 29.7 35.9
#> Ouvrier qualifie 292 14.6 17.7
#> Cadre 260 13.0 15.7
#> Ouvrier specialise 203 10.2 12.3
#> Profession intermediaire 160 8.0 9.7
#> Technicien 86 4.3 5.2
#> Autre 58 2.9 3.5
#> NA 347 17.3 NA

hdv2003$newqualif <- forcats::fct_lump_prop(hdv2003$qualif, 0.06)
freq(hdv2003$newqualif, sort = "dec")

#> n % val%
#> Employe 594 29.7 35.9
#> Ouvrier qualifie 292 14.6 17.7
#> Cadre 260 13.0 15.7
#> Ouvrier specialise 203 10.2 12.3
#> Profession intermediaire 160 8.0 9.7
#> Other 144 7.2 8.7
#> NA 347 17.3 NA

关于r - 根据频率更改 R 中数据帧的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62429843/

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