Move a column to first position in a data frame

前端 未结 8 1516
别那么骄傲
别那么骄傲 2020-12-22 23:30

I would like to have the last column of the data frame moved to the start (as first column). How can I do it in R?

My data.frame has about a thousand columns to chan

8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-23 00:18

    A native R approach that works with any number of rows or columns to move the last column of a dataframe to the first column position:

    df <- df[,c(ncol(df),1:ncol(df)-1)]
    

    It can be used to move any column to the first column by replacing:

    df <- df[,c(your_column_number_here,1:ncol(df)-1)]
    

    If you don't know the column number, but know the column label name, do the following replacing "your_column_name_here":

    columnNumber <- which(colnames(df)=="your_column_name_here")
    df <- df[,c(columnNumber,1:ncol(df)-1)]
    

提交回复
热议问题