我有一个类似的“ main_df”,其中每个别名都包含一个不正确的网址代码:
main_df <- tibble("eW1BRoUDV4BKQMl" = c("word", "word", "word", "word", "word"),
"5zKTGwHlwlzpssB" = c("word", "word", "word", "word", "word"),
"55SVfoQudZJNCFT" = c("word", "word", "word", "word", "word"),
"bOORR1zuKYSnAe9" = c("word", "word", "word", "word", "word"),
"6RrOQfDZim81pHv" = c("word", "word", "word", "word", "word"))
# A tibble: 5 x 5
eW1BRoUDV4BKQMl `5zKTGwHlwlzpssB` `55SVfoQudZJNCFT` bOORR1zuKYSnAe9 `6RrOQfDZim81pHv`
<chr> <chr> <chr> <chr> <chr>
1 word word word word word
2 word word word word word
3 word word word word word
4 word word word word word
5 word word word word word
我还有第二个“ reference_df”,其中也包含相同的唯一网址以及相应的明智的“商品”名称:
reference_df <- tibble(item = c("ashtray", "bell", "blouse", "boot", "bottle"),
url = c("eW1BRoUDV4BKQMl", "5zKTGwHlwlzpssB", "55SVfoQudZJNCFT", "bOORR1zuKYSnAe9", "6RrOQfDZim81pHv"))
# A tibble: 5 x 2
item url
<chr> <chr>
1 ashtray eW1BRoUDV4BKQMl
2 bell 5zKTGwHlwlzpssB
3 blouse 55SVfoQudZJNCFT
4 boot bOORR1zuKYSnAe9
5 bottle 6RrOQfDZim81pHv
我需要将“ main_df”的名称与“ reference_df $ url”中的值进行匹配,如果找到,请用“ reference_df $ item”替换“ main_df”的名称。因此,我的“ main_df”的期望输出为:
# A tibble: 5 x 5
ashtray bell blouse boot bottle
<chr> <chr> <chr> <chr> <chr>
1 word word word word word
2 word word word word word
3 word word word word word
4 word word word word word
5 word word word word word
我可能可以通过for循环来做到这一点,但是我想知道是否有解决办法。 tidyverse解决方案将是更好的选择-我很确定我应该使用apply或map_df(),但我无法弄清楚。
任何帮助将不胜感激!
答案 0 :(得分:2)
我们可以用match
的{{1}} main_df
的列名url
并更改reference_df
的名称。
main_df
一种names(main_df) <- reference_df$item[match(names(main_df), reference_df$url)]
# ashtray bell blouse boot bottle
# <chr> <chr> <chr> <chr> <chr>
#1 word word word word word
#2 word word word word word
#3 word word word word word
#4 word word word word word
#5 word word word word word
方法是根据dplyr
中的url
排列列并重命名。
reference_df