Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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
like image 964
t-kalinowski Avatar asked Sep 22 '16 15:09

t-kalinowski


1 Answers

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")]
like image 81
Pierre L Avatar answered Oct 07 '22 13:10

Pierre L