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

时间:2020-06-17 13:11:32

标签: r dataframe replace

我正在尝试将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")

1 个答案:

答案 0 :(得分:0)

缺少您的数据和我可以提供的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