I have three variables in a data frame and would like to swap the 4 columns around from
\"dam\" \"piglet\" \"fdate\" \"ssire\"
to
I noticed that this is almost an 8-year old question. But for people who are starting to learn R and might stumble upon this question, like I did, you can now use a much flexible select()
function from dplyr
package to accomplish the swapping operation as follows.
# Install and load the dplyr package
install.packages("dplyr")
library("dplyr")
# Override the existing data frame with the desired column order
df <- select(df, piglet, ssire, dam, tdate)
This approach has following advantages:
select()
does not require variable names to be enclosed within quotes.starts_with()
, ends_with()
, etc. to select multiple columns without having to name each column and rearrange them with much ease.