简体   繁体   English

根据行值提取列

[英]extract column based on row values

Following Data Set: 以下数据集:

df <- read.table(text = "  a b c 
                 X Y Z", header = T)

The command 命令

 df[, sapply (df[1, ], as.character) %in% c("Y", "X")]

returns 退货

  a b
1 X Y

but the command 但是命令

df[, sapply (df[1, ], as.character) %in% c("Y")]

returns 退货

[1] Y
Levels: Y

and not 并不是

   b
1  Y

Any idea why? 知道为什么吗? And how I can retrieve the correct column name 以及如何检索正确的列名

Likely a duplicate...but to provide an answer... 可能重复...但要提供答案...

You've fallen into one of the major traps of the R Inferno; 您已经掉入R Inferno的主要陷阱之一 8.1.44 where "By default dimensions of arrays are dropped when subscripting makes the dimension length 1. Subscripting with drop=FALSE overrides the default." 8.1.44 “在使用下标使尺寸长度为1时,默认情况下会删除数组的默认尺寸。使用drop = FALSE的下标将覆盖默认值。”

So, this will return what you expect: 因此,这将返回您期望的结果:

df[, sapply (df[1, ], as.character) %in% c("Y"), drop = FALSE]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM