Changing columns positions in a data frame without total reassignment

r

Solution

It's not a single function, but relatively simple:

dd[replace(seq(dd), 2:3, 3:2)]

  A   SO   Does
1 1 rock really
2 2 rock really
3 3 rock really
4 4 rock really

Problem

I want to swap two columns in a data.frame. I know I could do something like: ``` dd <- dd[c(1:4, 6:5, 7:10)] ``` But I find it inelegant, potentially slow (?) and not program-friendly (you need to know `length(dd)`, and even have some cases if the swapped columns are close or not to that value...) Is there an easy way to do it without reassigning the whole data frame? ``` dd[2:3] <- dd[3:2] ``` Turns out to be very "lossy" because the `[ <-` only concerns the values, and not the attributes. So for instance: ``` (dd <- data.frame( A = 1:4, Does = 'really', SO = 'rock' ) ) dd[3:2] dd[2:3] <- dd[2:1] print(dd) ``` The column names are obviously not flipped... Any idea? I could also add a small custom function to my very long list, but grrr... should be a way. ;-)

Original source

Related problems