Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing columns positions in a data frame without total reassignment

Tags:

r

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. ;-)

like image 676
Antoine Lizée Avatar asked Aug 09 '13 00:08

Antoine Lizée


2 Answers

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
like image 94
Sven Hohenstein Avatar answered Oct 25 '22 14:10

Sven Hohenstein


This:

dd[,2:3] <- dd[,3:2]

works, but you have to update the names as well:

names(dd)[2:3] <- names(dd)[3:2]
like image 2
Ferdinand.kraft Avatar answered Oct 25 '22 12:10

Ferdinand.kraft