按特定顺序选择R中的列(selecting columns in R in certain order)

编程入门 行业动态 更新时间:2024-10-07 06:44:39
按特定顺序选择R中的列(selecting columns in R in certain order)

我有一个包含大量列(+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])]

更多推荐

本文发布于:2023-07-27 04:04:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1284882.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:顺序   selecting   order   columns

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!