Change values of a dataframe in R depending on frequency

Viewed 62

I am trying to recode character values from a dataframe in R as:

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

So I would like to replace all "character" values in the dataframe where frequency is lower than 6% for "other", so the result would be:

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

Usually I do the replacement of values using replace as show next, but I would like to know if there is a better way to do it using the 6% value.

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

Absent your data and more info I can offer forcats::fct_lump_prop. Here's an example using the data set from questionr which is where I believe you're getting the freq function from.

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
Related