freeze_factor_levels: re-order factor levels in a data frame to their current...

Description Usage Arguments Value Author(s) See Also Examples

View source: R/freeze_factor_levels.R

Description

Takes a data frame and looks at each column. If the column is _not_ a factor, it will be returned unchanged. If the column is a factor, it will be replaced with a factor having the same levels, but re-ordered to whatever their observed current level in the data frame happens to be. It re-sets all the factors except those named in the "no_freeze" argument. Intended as an improvement on the older "freezeFactorLevels()".

Usage

1
freeze_factor_levels(x, no_freeze = NULL)

Arguments

x

a data frame.

no_freeze

character vector. Columns of "x" named in this vector will be returned unchanged.

Value

data frame of the same size, names, and types as "x". Factor level orders may have changed.

Author(s)

Bill Forrest forrest@gene.com

See Also

factor

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 myDat <- data.frame(
             animal = factor( c('cat', 'dog', 'cat', 'bird', 'fish', 'dog', 'cat'),
                              levels = c('bird','cat','dog','fish')
                            ),
             covering = factor( c('hair','hair', 'hair', 'feathers', 'scales', 'hair', 'hair'),
                                levels = c('feathers','hair','scales')
             ),
             feet = c(4,4,4,2,0,4,4)
          ) # end of data.frame 'myDat'


### Freeze all factors
myNewDat <- freeze_factor_levels( myDat )
print( levels( myDat$animal ) )
print( levels( myNewDat$animal) )
print( levels( myDat$covering ) )
print( levels( myNewDat$covering) )


### Freeze one but not another
myNewDat2 <- freeze_factor_levels( myDat, no_freeze = 'covering' )
print( levels( myDat$animal ) )
print( levels( myNewDat2$animal) )
print( levels( myDat$covering ) )
print( levels( myNewDat2$covering) )


### Freeze neither factor
myNewDat3 <- freeze_factor_levels( myDat, no_freeze = c('animal','covering') )
print( levels( myDat$animal ) )
print( levels( myNewDat3$animal) )
print( levels( myDat$covering ) )
print( levels( myNewDat3$covering) )

wfforrest/maeve documentation built on Jan. 1, 2021, 12:47 p.m.