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

前端 未结 7 2003
暖寄归人
暖寄归人 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:35

    Perhaps not the intention of the designers, but you can utilize the scoped verb rename_all and the dplyr function recode, which takes one or more key value pairs like old_name = "New Name".

    library(dplyr)
    
    rename_all(iris, recode, Sepal.Length = "sepal_length", cyl = "cylinder")
    #     sepal_length Sepal.Width Petal.Length Petal.Width    Species
    # 1            5.1         3.5          1.4         0.2     setosa
    # 2            4.9         3.0          1.4         0.2     setosa
    # 3            4.7         3.2          1.3         0.2     setosa
    # 4            4.6         3.1          1.5         0.2     setosa
    # 5            5.0         3.6          1.4         0.2     setosa
    # 6            5.4         3.9          1.7         0.4     setosa
    # 7            4.6         3.4          1.4         0.3     setosa
    # 8            5.0         3.4          1.5         0.2     setosa
    # 9            4.4         2.9          1.4         0.2     setosa
    

提交回复
热议问题