1

I have a table that looks like this:

V1 V2 V3 V4
E
O  W  I
F  A  Z  C
S  D  K  L

I want sort across/horizontally so that it looks like this:

V1 V2 V3 V4
E
I  O  W
A  C  F  Z
D  K  L  S

I tried using sort and order, but I can only get it to sort vertically or reorder entire columns. Is it possible to sort horizontally for individual row?

Thanks.

Note: I don't see the similarities between my question and "Sort data by row". The solution is not even the same.

Cinji18
  • 619
  • 8
  • 22

1 Answers1

3

You can try

df[] <- t(apply(df,1,function(x) c(sort(x[x!='']), x[x==''])))
df
#  V1 V2 V3 V4
#1  E         
#2  I  O  W   
#3  A  C  F  Z
#4  D  K  L  S

It may be also better to have missing elements as NA instead of ''

df[df==''] <- NA
df[] <- t(apply(df, 1, function(x) x[order(x)]))
df[is.na(df)] <- '' #if needed

data

df <- structure(list(V1 = c("E", "O", "F", "S"), V2 = c("", "W", "A", 
"D"), V3 = c("", "I", "Z", "K"), V4 = c("", "", "C", "L")), .Names = c("V1", 
"V2", "V3", "V4"), class = "data.frame", row.names = c(NA, -4L))
akrun
  • 874,273
  • 37
  • 540
  • 662