简体   繁体   中英

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

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")]

Just don't put the [] after the df and it will do as you want...

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

And if you question is about why, Pierre Lafortune's comment is right.

as a side note, I also like to add the commat to separate dimension:

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

I find it more proper.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM