I have some simple data frames of n columns. For each of them, I want to move the last column to the first. Since number of columns is variable, I used:
df <- df[, c(ncol(df), 1:(ncol(df)-1))]
=========================================================
However, I do not understand why both c(12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
and c(ncol(df), 1:(ncol(df)-1))
returns
[1] 12 1 2 3 4 5 6 7 8 9 10 11
and df[, c(12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)]
can return the reordered table I want,
but
df[, c(ncol(df), 1:(ncol(df)-1))]
returns the above vector of indices instead of the reordered table
Thanks!
===============================================================
EDIT:
reproducible example below:
df <- data.table(v1=c(1,2), v2=c(3,4), v3=c(5,6))
c(3,1,2)
c(ncol(df), 1:(ncol(df)-1))
df2 <- df[, c(3,1,2)]
df2
df3 <- df[, c(ncol(df), 1:(ncol(df)-1))]
df3