问题描述
我有一个遵循相同顺序的较大数据集,一个唯一的日期列,数据,唯一的日期列,日期等。我试图不仅按名称对数据列进行子集化,而且还对唯一的日期列进行子集化。下面的代码根据名称列表选择列,这是我想要的一部分,但是关于如何在紧接子集列之前也可以立即获取列的任何想法?
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 unique date column also. The code below selects columns based on a list of names, which is part of what I want but any ideas of how I can grab the column immediately before the subsetted column also?
最后要使用包含Date1,Fire,Date3,Earth列的DF(仅使用NameList)。
Looking to end up with a DF containing Date1, Fire, Date3, Earth columns (using just the NameList).
这是我可复制的代码:
Cnames <- c("Date1","Fire","Date2","Water","Date3","Earth")
MAINDF <- data.frame(replicate(6,runif(120,-0.03,0.03)))
colnames(MAINDF) <- Cnames
NameList <- c("Fire","Earth")
NewDF <- MAINDF[,colnames(MAINDF) %in% NameList]
推荐答案
如何
NameList <- c("Fire","Earth")
idx <- match(NameList, names(MAINDF))
idx <- sort(c(idx-1, idx))
NewDF <- MAINDF[,idx]
此处我们使用 match()
查找所需列的索引,然后我们可以使用索引减法在列之前抢先
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
这篇关于根据列名称列表对列进行子集设置,并将其置于列之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!