How to drop columns by name pattern in R?

前端 未结 5 1970
忘掉有多难
忘掉有多难 2020-11-28 08:23

I have this dataframe:

state county city  region  mmatrix  X1 X2 X3    A1     A2     A3      B1     B2     B3      C1      C2      C3

  1      1     1            


        
5条回答
  •  暖寄归人
    2020-11-28 08:41

    Your code works like a charm if I apply it to a minimal example and just search for the string "A":

    df <- data.frame(ID = 1:10,
                     A1 = rnorm(10),
                     A2 = rnorm(10),
                     B1 = letters[1:10],
                     B2 = letters[11:20])
    df[, -grep("A", colnames(df))]
    

    So your problem is more a regular expression problem, not how to drop columns. If I run your code, I get an error:

    df[, -grep("\\3$", colnames(df))]
    Error in grep("\\3$", colnames(df)) : 
      invalid regular expression '\3$', reason 'Invalid back reference'
    

    Update: Why don't you just use this following expression?

    df[, -grep("1$", colnames(df))]
       ID         A2 B2
    1   1  2.0957940  k
    2   2 -1.7177042  l
    3   3 -0.0448357  m
    4   4  1.2899925  n
    5   5  0.7569659  o
    6   6 -0.5048024  p
    7   7  0.6929080  q
    8   8 -0.5116399  r
    9   9 -1.2621066  s
    10 10  0.7664955  t
    

提交回复
热议问题