Avoiding error when using rename in dplyr and column doesn't exist

前端 未结 7 1995
暖寄归人
暖寄归人 2021-02-07 03:15

Is there a clever way to use the rename function in dplyr when in some instances the column to be renamed doesn\'t exist?

For example, I would like the following not to

7条回答
  •  执念已碎
    2021-02-07 03:29

    Sometimes it's okay to not do everything in dplyr. This may be one of those times. I would set up a vector that operates as a key:

    namekey <- c(mpg="miles_per_gallon", cyl="cylinders", disp="displacement", hp="horse_power",
                 drat="rear_axle_ratio", wt="weight", qsec="quarter_mile_time", vs="v_s",
                 am="transmission", gear="number_of_gears", carb="number_of_carburetors",
                 foo="missing_variable")
    
    mtcars1 <- mtcars[,1:2]
    mtcars1$foo <- rnorm(nrow(mtcars1))
    
    names(mtcars1) <- namekey[names(mtcars1)]
    
    head(mtcars1)
    #                   miles_per_gallon cylinders missing_variable
    # Mazda RX4                     21.0         6       -0.9901081
    # Mazda RX4 Wag                 21.0         6        0.2338014
    # Datsun 710                    22.8         4       -0.3077473
    # Hornet 4 Drive                21.4         6        1.1200518
    # Hornet Sportabout             18.7         8        0.7482842
    # Valiant                       18.1         6        0.4206614
    

    Once you have your key, it's just a single, easy-to-understand line of code that does the rename.

提交回复
热议问题