我有一个包含大量列(+300)的数据集。 我只对其中的一些感兴趣。 我用这种方式选择了这些:
ks2reduced <- ks2data[,ks2meta[,2]]其中ks2meta [,2]包含我感兴趣的列的名称。这有效但问题是结果数据框的列的顺序与ks2meta [,2]中设置的顺序不同:
> ks2meta[,2] [1] RECTYPE LEA ESTAB URN SCHNAME [6] .. > colnames(ks2reduced) [1] "TAB1618" "LEA" "ALPHAIND" "TKS1APS" "TPUPYEAR" "PBELIG" "URN" [6] ..实际上,我对R的这种行为感到惊讶 - 对我来说它似乎是一种“语言陷阱”(行为可能是解释但未预期)。 如何以与向量中列出的顺序相同的顺序选择列?
I have a dataset with a large number of columns (+300). I am interested only in a few of them. I selected these in this way:
ks2reduced <- ks2data[,ks2meta[,2]]where ks2meta[,2] contains the names of the columns I am interested in. This works but the problem is that the resulting data frame has the columns in a different order than the order set in ks2meta[,2]:
> ks2meta[,2] [1] RECTYPE LEA ESTAB URN SCHNAME [6] .. > colnames(ks2reduced) [1] "TAB1618" "LEA" "ALPHAIND" "TKS1APS" "TPUPYEAR" "PBELIG" "URN" [6] ..I am, actually, surprised by this behaviour of R - to me it seems to be a "language gotcha" (behaviour that is probably explained but not expected). How can I select the columns in the same order as they are listed in a vector?
最满意答案
可能是因为你的矢量是一个因素,而不是一个字符:
ks2reduced <- ks2data[,as.character(ks2meta[,2])]probably because your vector is a factor and not a character :
ks2reduced <- ks2data[,as.character(ks2meta[,2])]更多推荐
发布评论