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

前端 未结 2 1712

For example, with the data set mtcars

mtcars[ , \"cyl\"]

and

mtcars[ , 2]

both give me the

相关标签:
2条回答
  • 2021-01-01 12:42

    I often use subset. An example using mtcars

    > names(mtcars)
     [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear" "carb"
    > cars <- subset(mtcars, select=-c(mpg,cyl))
    > names(cars)
    [1] "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear" "carb"
    

    There are some other ideas in the answers to this question.

    Update: Subset also works for temporary removal of one or more columns by name, just replace mtcars[,-2] with subset(mtcars, select=-cyl).

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题