Mark
Mark

Reputation: 1769

How to rearrange the entries (character) in each row of a dataframe according to the alphabetical order?

I have a data.frame like this:

df=data.frame(word1 = c("hello", "red", "red"), word2 = c("world", "hello", "yellow"), word3 = 
                   c("red", "world", "hello"), n = c(574L, 306L, 302L))

i.e.

> df
  word1  word2 word3   n
1 hello  world   red 574
2   red  hello world 306
3   red yellow hello 302

I would like to rearrange the words in each row according to the alphabetical order. For example:

> df_new
  word1 word2 word3    n
1 hello   red world  574
2 hello   red world  306
3 hello   red yellow 302

Upvotes: 1

Views: 36

Answers (1)

akrun
akrun

Reputation: 887128

Loop over the rows with apply on the selected column, sort and update those columns

df[1:3] <- t(apply(df[1:3], 1, sort))

Or using dplyr/tidyr

library(dplyr)
library(tidyr)
df %>% 
   rowwise %>% 
   transmute(out = list(sort(c_across(where(is.character)))), n) %>% 
   ungroup %>%
   unnest_wider(c(out), names_repair =  ~names(df))

Upvotes: 1

Related Questions