Deleting multiple columns in R

前端 未结 4 1429
青春惊慌失措
青春惊慌失措 2021-01-27 11:29

I have a dataframe df with column names from m1 to m100

I want to delete columns in the range m50 to m100. Is there a faster way to do it than hardcoding it

4条回答
  •  南方客
    南方客 (楼主)
    2021-01-27 12:01

    More eloquently put, without using any external packages or extra function calls, just use R's logical subsets:

    mydf <- data.frame(matrix(1:100, ncol = 100, 
                              dimnames = list(NULL, paste0("M", 1:100))))
    
    mydf[,1:49]
    

    yielding:

    > mydf[,1:49]
      m1 m2 m3 m4 m5 m6 m7 m8 m9 m10 m11 m12 m13 m14 m15 m16 m17 m18 m19 m20 m21 m22
    1  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22
      m23 m24 m25 m26 m27 m28 m29 m30 m31 m32 m33 m34 m35 m36 m37 m38 m39 m40 m41 m42
    1  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42
      m43 m44 m45 m46 m47 m48 m49
    1  43  44  45  46  47  48  49
    

提交回复
热议问题