ft_pos | R Documentation |
Reorders the levels of a factor vector based on characters extracted from specified positions within each level's name. Supports case sensitivity, descending order, and optionally reorders the data vector's elements to align with the new levels' order.
ft_pos(
factor_vec,
positions,
case = FALSE,
decreasing = FALSE,
inplace = FALSE
)
factor_vec |
A factor vector whose levels will be reordered. |
positions |
An integer vector specifying the character positions to extract from each level's name for ordering. |
case |
Logical. If |
decreasing |
Logical. If |
inplace |
Logical. If |
A new factor vector with reordered levels. Depending on the inplace
parameter, the data vector's elements may also be reordered.
Kai Guo
# Example 1: Reorder levels based on characters at positions 2 and 4
# without reordering data elements
factor_vec <- factor(c('apple', 'banana', 'cherry', 'date', 'fig', 'grape'))
new <- ft_pos(
factor_vec,
positions = c(2, 4),
case = FALSE,
decreasing = FALSE,
inplace = FALSE
)
print(new)
# [1] apple banana cherry date fig grape
# Levels: apple banana date cherry fig grape
# Example 2: Reorder levels based on characters at positions 2 and 4
# and reorder data elements
new_inplace <- ft_pos(
factor_vec,
positions = c(2, 4),
case = FALSE,
decreasing = FALSE,
inplace = TRUE
)
print(new_inplace)
# [1] apple banana date cherry fig grape
# Levels: apple banana date cherry fig grape
# Example 3: Reorder levels in decreasing order based on characters at
# positions 1 and 3 without reordering data elements
new_dec <- ft_pos(
factor_vec,
positions = c(1, 3),
case = FALSE,
decreasing = TRUE,
inplace = FALSE
)
print(new_dec)
# [1] apple banana cherry date fig grape
# Levels: grape fig date cherry banana apple
# Example 4: Reorder levels with case sensitivity and reorder data elements
factor_vec_case <- factor(c('Apple', 'banana', 'Cherry', 'date', 'Fig', 'grape'))
new_case <- ft_pos(
factor_vec_case,
positions = c(1, 2),
case = TRUE,
decreasing = FALSE,
inplace = TRUE
)
print(new_case)
# [1] Apple banana Cherry date Fig grape
# Levels: Apple banana Cherry date Fig grape
# Example 5: Reorder levels based on characters at positions 3, allowing
# insertion at positions beyond string length
factor_vec_short <- factor(c('go', 'dog', 'cat', 'bird'))
new_short <- ft_pos(
factor_vec_short,
positions = c(3),
case = FALSE,
decreasing = FALSE,
inplace = FALSE
)
print(new_short)
# [1] go dog cat bird
# Levels: cat dog bird go
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.