forcats_fct_multi
In [1]:
Copied!
%run nb_helpers.py
from datar.all import *
nb_header(
fct_c,
fct_cross,
book="forcat_fct_multi",
)
%run nb_helpers.py
from datar.all import *
nb_header(
fct_c,
fct_cross,
book="forcat_fct_multi",
)
Try this notebook on binder.
★ fct_c¶
★ fct_cross¶
Combine levels from two or more factors to create a new factor¶
Computes a factor whose levels are all the combinations of
the levels of the input factors.
Args:¶
*fs
: factors to cross
sep
: A string to separate levels
keep_empty
: If True, keep combinations with no observations as levels
Returns:¶
The new factor
fct_c¶
In [2]:
Copied!
fa = factor("a")
fb = factor("b")
fab = factor(c("a", "b"))
# c(fa, fb, fab)
# convert factor to integer for `c`?
fa = factor("a")
fb = factor("b")
fab = factor(c("a", "b"))
# c(fa, fb, fab)
# convert factor to integer for `c`?
In [3]:
Copied!
fct_c(fa, fb, fab)
fct_c(fa, fb, fab)
Out[3]:
['a', 'b', 'a', 'b'] Categories (2, object): ['a', 'b']
In [4]:
Copied!
fs = [fa, fb, fab]
fct_c(*fs)
fs = [fa, fb, fab]
fct_c(*fs)
Out[4]:
['a', 'b', 'a', 'b'] Categories (2, object): ['a', 'b']
fct_cross¶
In [5]:
Copied!
fruit = factor(c("apple", "kiwi", "apple", "apple"))
colour = factor(c("green", "green", "red", "green"))
eaten = c("yes", "no", "yes", "no")
fct_cross(fruit, colour)
fruit = factor(c("apple", "kiwi", "apple", "apple"))
colour = factor(c("green", "green", "red", "green"))
eaten = c("yes", "no", "yes", "no")
fct_cross(fruit, colour)
Out[5]:
['apple:green', 'kiwi:green', 'apple:red', 'apple:green'] Categories (3, object): ['apple:green', 'apple:red', 'kiwi:green']
In [6]:
Copied!
fct_cross(fruit, colour, eaten)
fct_cross(fruit, colour, eaten)
Out[6]:
['apple:green:yes', 'kiwi:green:no', 'apple:red:yes', 'apple:green:no'] Categories (4, object): ['apple:green:no', 'apple:green:yes', 'apple:red:yes', 'kiwi:green:no']
In [7]:
Copied!
fct_cross(fruit, colour, keep_empty = TRUE)
fct_cross(fruit, colour, keep_empty = TRUE)
Out[7]:
['apple:green', 'kiwi:green', 'apple:red', 'apple:green'] Categories (4, object): ['apple:green', 'apple:red', 'kiwi:green', 'kiwi:red']