在dplyr中使用重命名和列不存在时避免错误 [英] Avoiding error when using rename in dplyr and column doesn't exist
问题描述
在某些情况下,不存在在dplyr中使用重命名功能的聪明方法吗?
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 result in an error
mtcars%>%rename(miles_per_gallon=mpg,missing_varible=foo)
(结果:错误:未知变量:foo。)
(results in this: Error: Unknown variables: foo.)
,而是完成了所有可能的重命名的数据框。
but rather the dataframe with all possible renaming done.
当前,我正在重命名之前明确检查特定列是否存在
Currently I am explicitly checking that the specific column exists before renaming
谢谢
伊恩
推荐答案
有时可以不执行 dplyr
中的所有操作。这可能是其中之一。我将设置一个用作键的向量:
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.
这篇关于在dplyr中使用重命名和列不存在时避免错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!