Speed up sorting algorithm in R: make one column "smaller" than the other Consider the following sorting algorithm:

df &lt;- data.frame(food_1 = c("APPLE 1534", "PEAR 2525", "BANANA 3045", "WATERMELON 5000"),
                 food_2 = c("ORANGE 2035", "BROCCOLI 5000", "BLUEBERRY 2000", "TOMATO 3000"),
                 stringsAsFactors = FALSE)

# Sorting
for (i in 1:nrow(df)){
  foods &lt;- sort(c(df$food_1[i], df$food_2[i]))
  df$food_1[i] &lt;- foods[1]
  df$food_2[i] &lt;- foods[2]
}


I have data frames which are of size 250,000+ rows that I've used the code above for, and I'm not sure how to make this more efficient.
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)