R:根据列内容有条件地提取列名称

时间:2018-06-01 09:09:17

标签: r

我有一个这样的数据框:

structure(list(id = 1:10, emrA = c("I219V, T286A", "1", "0", 
"I219V", "I219V", "R164H, I219V", "R164H, I219V", "R164H, I219V", 
"R164H, I219V", "R164H, I219V"), gyrA_8 = c("S83L,678E", "D87N", 
"S83L,252G", "S83L,678E", "S83L,678E", "S83L,828T", "S83L,828T", 
"S83L,828T", "S83L,828T", "S83L,828T"), emrY = c("0", "1", "1", 
"1", "1", "1", "1", "1", "1", "1"), T_CIP = c(0.25, 0.12, 0.12, 
0.25, 0.25, 0.5, 2, 1, 1, 2)), .Names = c("id", "emrA", "gyrA_8", 
"emrY", "T_CIP"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -10L))

看起来像这样:

     id emrA         gyrA_8    emrY  T_CIP
      1 I219V, T286A S83L,678E 0     0.25
      2 1            D87N      1     0.12
      3 0            S83L,252G 1     0.12
      4 I219V        S83L,678E 1     0.25
      5 I219V        S83L,678E 1     0.25
      6 R164H, I219V S83L,828T 1     0.5
      7 R164H, I219V S83L,828T 1     2
      8 R164H, I219V S83L,828T 1     1
      9 R164H, I219V S83L,828T 1     1
     10 R164H, I219V S83L,828T 1     2

我想创建一个带有不包含1/0的列名称的向量。

我想得到什么:

vector: c("id", "emrA", "gyrA_8", "T_CIP")

我试图在没有运气的情况下使用这样的东西:

lapply(df, function(x) colnames(which(grepl("regex_pattern", x) == TRUE))

2 个答案:

答案 0 :(得分:1)

如果df是你的dataframe,那么你可以这样做:

output <- df[,!sapply(df, function(x) all(x %in% c(0,1)))]

这将为您提供那些不包含0或1的列。

如果您想要列名称,则可以执行names(output)colnames(output)

答案 1 :(得分:0)

我们也可以使用foo = c(1, 2, 3) bar = c(1, "AB", 3) df = data.frame(foo,bar,stringsAsFactors=FALSE) df%>% mutate(bar=if_else(!is.na(as.numeric(bar)),as.numeric(bar)/100,bar))

Filter