Is it possible to swap columns around in a data frame using R?

后端 未结 7 2009
野的像风
野的像风 2020-12-08 19:54

I have three variables in a data frame and would like to swap the 4 columns around from

\"dam\"   \"piglet\"   \"fdate\"   \"ssire\"

to

相关标签:
7条回答
  • 2020-12-08 20:42

    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:

    1. You will have to type less as the select() does not require variable names to be enclosed within quotes.
    2. In case your data frame has more than 4 variables, you can utilize select helper functions such as starts_with(), ends_with(), etc. to select multiple columns without having to name each column and rearrange them with much ease.
    0 讨论(0)
提交回复
热议问题