I would like to change the names of a tibble using another tibble which work as a dictionary.
however, I don't know if the order of the table's variables are the same as the dictionary's rows.
The only thing assured is that the first variable of the names table holds all the variable names in the data
examples:
in the simplest case (not this problem) the order of the variables is equal to the ordering of the dictionary's rows
cars <- as_tibble(mtcars)
wanted_names <- tribble(~names, ~new,
"mpg","arbitary1",
"cyl","arbitary2",
"disp","x",
"hp","y",
"drat","f",
"wt","sss",
"qsec","ffff",
"vs","wvegsb",
"am","dhyhjn",
"gear","scsssfsf",
"carb","arbitaryn")
names(cars)
[1] "mpg" "cyl" "disp" "hp" "drat" "wt" "qsec" "vs" "am" "gear" "carb"
I could just use-
names(cars)<-wanted_names$new
yet I cannot vouch for the order of wanted_names
or cars
, so it actually looks similar to this:
cars <- as_tibble(mtcars) %>%
select(wt,hp,carb,everything())
wanted_names <- tribble(~names, ~new,
"wt","sss",
"qsec","ffff",
"vs","wvegsb",
"am","dhyhjn",
"disp","x",
"hp","y",
"drat","f",
"cyl","arbitary2",
"gear","scsssfsf",
"mpg","arbitary1",
"carb","arbitaryn")
any method that could assure correct renaming will be appreciated.
carsNew <- dplyr::left_join(cars, wanted_names, by = "names") %>% select(-names)
– SKyJim