t.kalinowski t.kalinowski - 2 months ago 5
R Question

Why doesn't `[<-` work to reorder data frame columns?

Why doesn't this work?

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


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

This works just fine

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

Answer

When an extraction is completed the values in the index are replaced not the names. For example, replacing the first item below does not affect the name of the element:

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

In your data frame you replaced the values in the same way. The values changed but the names stayed constant. To reorder the data frame avoid the extraction framework.

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