1
votes

I would like to do a row-wise sort using specific columns but also retain all columns from the original df.

Data:

df <- structure(list(C1 = c("ABC", "XYZ", "DEF"),
                           C2 = c("ZLO", "BCD", "PQR"),
                           C3 = c("E1", "E2", "E3")),
                           class = "data.frame", row.names = c(NA, -3L))

Desired output:
C1  C2  C3
ABC ZLO E1
BCD XYZ E2
DEF PQR E3

I tried to do this using:

df <- t(apply(df[1:2], 1, 
                   FUN=function(x) sort(x, decreasing=FALSE)))

but it only returns the first two columns and I need help to: a) vectorize it b) retain all columns

3

3 Answers

3
votes
df <- structure(list(C1 = c("ABC", "XYZ", "DEF"),
                     C2 = c("ZLO", "BCD", "PQR"),
                     C3 = c("E1", "E2", "E3")),
                class = "data.frame", row.names = c(NA, -3L))

Solution usign dplyr and tidyr to bring data into long form, group it by row and sort it by the strings and then bring it back into wide form:

library(dplyr)
library(tidyr)

Edit:

Edited code so C3 remains as it is

df %>% 
  mutate(ID = row_number()) %>% 
  pivot_longer(cols=-c(ID, C3)) %>% 
  group_by(ID) %>% 
  arrange(value) %>% 
  mutate(name = paste0("C", row_number())) %>% 
  pivot_wider(names_from = name,
              values_from = value) %>% 
  select(C1, C2, C3)


# Groups:   ID [3]
     ID C1    C2    C3   
  <int> <chr> <chr> <chr>
1     1 ABC   ZLO   E1   
2     2 BCD   XYZ   E2   
3     3 DEF   PQR   E3 
1
votes

Instead of assigning to df, only assign to the columns you want to sort.

df[1:2] <- t(apply(df[1:2], 1, 
              FUN=function(x) sort(x, decreasing=FALSE)))

Or written more simply:

to_sort <- 1:2
df[to_sort] <- t(apply(df[to_sort], 1, sort, decreasing = FALSE))
0
votes

Here is another solution:

  librar(dplyr)
  df <- apply(df[1:2], 1, sort) %>% 
    t() %>% 
    cbind(df[3]) %>% 
    as.data.frame() %>% 
    setNames(paste0("C", 1:length(.)))

# output
     C1  C2 C3
  1 ABC ZLO E1
  2 BCD XYZ E2
  3 DEF PQR E3