How can I get a dataframe with columns temporarily removed by name?

前端 未结 2 1714

For example, with the data set mtcars

mtcars[ , \"cyl\"]

and

mtcars[ , 2]

both give me the

2条回答
  •  梦谈多话
    2021-01-01 12:44

    [Edit:] Explanation of why negative string indices does not work:

    -() is a function and the R developers say it can't be used on a character vector (and not just because negating a string doesn't make sense). Because you can't negate a character vector, you can't supply negative strings to drop columns. The problem is with - and is the source of the error message you quote. Hence the rule that negative indices only work for numerics. The source of the original error is:

    > -"cyl"
    Error in -"cyl" : invalid argument to unary operator
    

    Note that in the comments to the Q, there was confusion that the negative version of "cyl" was "-cyl", which it isn't, it is just another string. The R snippet above shows what was happening in the subsetting tried in the Question.

    Section 2.7 of the "An Introduction to R" manual describes the allowed methods of subsetting.

    [Original:] The simplest way to remove a component is just to set that component to NULL:

    > cars <- mtcars
    > cars[, "cyl"] <- NULL ## or cars$cyl <- NULL
    > names(cars)
     [1] "mpg"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear" "carb"
    

    [Edit:] In light of the Edit to the Q indicating a temporary drop of the named column was desired, then:

    subset(mtcars, select = -cyl)
    

    or

    mtcars[, !names(mtcars) %in% "cyl"]
    

    are options, and the former cleaner than the latter.

提交回复
热议问题