0

When I try to partially reorder columns using "[", the values are swaped but the column's names do not move. See the example below:

x = data.frame(x1 = c(1,2,3), x2 = c(2,3,4), x3 = c("e","e","e"), x4 = c("f","f","f"))

x
#x1 x2 x3 x4
#1  2  e  f
#2  3  e  f
#3  4  e  f

x[, c(3,4)] = x[, c(4,3)]
#x1 x2 x3 x4
#1  2  f  e
#2  3  f  e
#3  4  f  e

Any idea as to why the column's names are not moving and how to simply solve this ?

user2100721
  • 3,557
  • 2
  • 20
  • 29
Yohan Obadia
  • 2,552
  • 2
  • 24
  • 31
  • 2
    Switching the names might be more reasonable. `names(x)[c(3,4)] <- names(x)[c(4,3)]` – Psidom Aug 10 '16 at 16:21
  • @DavidArenburg I don't think this is a dupe of the link – akrun Aug 10 '16 at 17:23
  • 1
    @DavidArenburg This is not a duplicate at all. All questions related to column swaping are not the same. – Yohan Obadia Aug 10 '16 at 17:53
  • 2
    @YohanObadia if you want to know the "*why*"- simple. You are assigning *values* from `x[, c(4,3)]` to `x[, c(3,4)]` *columns*. This is how it works. `[]` preserves the original structure of `x`. This is the same as you would do `x[] <- lapply(x, type.convert)`. Although `lapply` returns a list rather a `data.frame`, `x` remains a `data.frame`. Other than that, all the answers in that dupe are relevant to your question – David Arenburg Aug 10 '16 at 17:59

2 Answers2

0

One option is cbind

x1 <- cbind(x[1:2], x[4:3])
x1
#  x1 x2 x4 x3
#1  1  2  f  e
#2  2  3  f  e
#3  3  4  f  e

Or we can also use numeric ordering


By doing the assignment, we are changing only the values and not the column names. The column values does change by position, but it will not translate by swapping the column names as column name is fixed for that position.

akrun
  • 874,273
  • 37
  • 540
  • 662
  • This is clever, thanks. However before I mark it as answered, could you please elaborate as to why what I was writting only changes the values when `x[, c(4,3)]` clearly contains the name of the columns. – Yohan Obadia Aug 10 '16 at 17:51
  • @YohanObadia The assignment is changing only the values of the columns by swapping. If we need to change the names, it has to be done separately as the column name is kind of an identity for that column. – akrun Aug 10 '16 at 18:05
0

Try this

x <- x[,c(1,2,4,3)]
user2100721
  • 3,557
  • 2
  • 20
  • 29
  • This works but it is not really what I wanted. I am rather curious as to why it does not work the way I do it. @akrun answer tackles it a bit more completely. – Yohan Obadia Aug 10 '16 at 17:48