r - Why doesn't `[<-` work to reorder data frame columns? -
why doesn't 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 names in original order, data has changed order.
this works 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 extraction completed values in index replaced not names. example, replacing first item below not affect name of element:
x <- c(a=1, b=2) x[1] <- 3 x b 3 2
in data frame replaced values in same way. values changed names stayed constant. reorder data frame avoid extraction framework.
df <- df[c("z", "y", "x")]
Comments
Post a Comment