Speed up sorting algorithm in R: make one column "smaller" than the other
You solution does the job, but it is often better to vectorise your code. See the following example. First get the ordering of all elements in column a and b and then use this to rearrange the elements in the data.frame. 

library(tictoc) #to get the run time

df &lt;- data.frame(a = runif(10000),
                 b = runif(10000))

# your solution
tic()
df.loop &lt;- df
for (i in 1:nrow(df.loop)){
df.loop[i, ] &lt;- sort(df.loop[i, ])
}
toc()

#sort (order) only once
tic()
index.a &lt;- 1:nrow(df)
index.b &lt;- (nrow(df) + 1) : (2*nrow(df))
a.b.ordered &lt;- order(c(df[, 1], df[, 2]))
b.greater.a &lt;- match(index.b, a.b.ordered) &lt; match(index.a, a.b.ordered)
df.index &lt;- df
df.index[b.greater.a, 1] &lt;- df[b.greater.a, 2]
df.index[b.greater.a, 2] &lt;- df[b.greater.a, 1]
toc()

identical(df.loop, df.index)