R tips: Swapping columns in a matrix

2009-03-31 15:59:00 Allan Engelhardt wrote in CYBAEA Data and Analysis:

Using R, the statistical analysis and computing platform, swapping two columns in a matrix is really easy: m[ , c(1,2)] <- m[ , c(2,1)].

Note, however, that this does not swap the column names (if you have any) but only the values. You could do something like colnames(m)[c(1,2)] <- colnames(m)[c(2,1)] if you need the names changed as well, but better is perhaps just to assign:

m <- m[ , c(2, 1, 3:ncol(m)) ]

Subscribe to CYBAEA Data and Analysis

Join the discussion

Do you agree or disagree? Have a question of want to make a point? Join the discussion:

There are no comments yet. Be the first to comment.