# 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
Run the code above in your browser using DataLab