Subset columns based on list of column names and bring the column before it

后端 未结 2 939
日久生厌
日久生厌 2021-02-19 08:59

I have a larger dataset following the same order, a unique date column, data, unique date column, date, etc. I am trying to subset not just the data column by name but the uniqu

2条回答
  •  情深已故
    2021-02-19 09:45

    Use which to get the column numbers from the names, and then it's just simple arithmetic:

    col.num <- which(colnames(MAINDF) %in% NameList)
    NewDF <- MAINDF[,sort(c(col.num, col.num - 1))]
    

    Produces

             Date1         Fire        Date3        Earth
    1 -0.010908003  0.007700453 -0.022778726 -0.016413307
    2  0.022300509  0.021341360  0.014204445 -0.004492150
    3 -0.021544992  0.014187158 -0.015174048 -0.000495121
    4 -0.010600955 -0.006960160 -0.024535954 -0.024210771
    5 -0.004694499  0.007198620  0.005543146 -0.021676692
    6 -0.010623787  0.015977135 -0.027741109 -0.021102651
    ...
    

提交回复
热议问题