Why does `[<-`` work to reorder columns of data frames?

Why is this not working?

 df <- data.frame(x=1:2, y = 3:4, z = 5:6) df[] <- df[c("z", "y", "x")] df #> xyz #> 1 5 3 1 #> 2 6 4 2 

note that the names are in the original order, but the data itself has changed the order.

It works just fine.

 df <- data.frame(x=1:2, y = 3:4, z = 5:6) df[c("z", "y", "x")] #> zyx #> 1 5 3 1 #> 2 6 4 2 
+7
source share
2 answers

When extraction is complete, the values โ€‹โ€‹in the index are not replaced with names. For example, replacing the first element below does not affect the element name:

 x <- c(a=1, b=2) x[1] <- 3 x ab 3 2 

In your data frame, you replaced the values โ€‹โ€‹in the same way. The values โ€‹โ€‹have changed, but the names have remained unchanged. To reorder data frames, avoid the extraction frame.

 df <- df[c("z", "y", "x")] 
+6
source

Just don't put [] after df and it will do what you need ...

 df <- data.frame(x=1:2, y = 3:4, z = 5:6) df <- df[c("z", "y", "x")] df # zyx #1 5 3 1 #2 6 4 2 

And if you doubt why, Pierre Lafortunโ€™s comment is right.

as an additional note, I would also like to add a comma to a separate size:

 df <- df[,c("z", "y", "x")] 

I think this is more correct.

0
source

All Articles