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

早过忘川 提交于 2019-12-04 02:22:23

How about

NameList <- c("Fire","Earth")

idx <- match(NameList, names(MAINDF))
idx <- sort(c(idx-1, idx))

NewDF <- MAINDF[,idx] 

Here we use match() to find the index of the desired column, and then we can use index subtraction to grab the column before it

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
...
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!