【问题标题】:Replace region numbers with names [duplicate]用名称替换区域编号[重复]
【发布时间】:2020-04-16 17:53:08
【问题描述】:
regions_numbers <- c(2,9,21,142,150,419)
regions_names <- c("Oceania", "Africa", "North America", "Asia", "Europe", "Latin America")

我需要将数字替换为对应的区域名称,但我不确定要使用什么代码

【问题讨论】:

  • 为了澄清,你是说你想用“Oceania”替换数字“2”。或者说,“150”和“欧洲”。因此,如果那时,我们引入一个新向量,比如eg&lt;-c(142,142,142),你想要一个新向量,而不是c("Asia","Asia","Asia")
  • 是的,完全正确。这些数字中的每一个都对应于各自的区域
  • 数字位于名为“区域”的列中。我想用对应的名字替换列中的数字

标签: r tidyverse


【解决方案1】:

我敢肯定有很多方法,但我想尽办法使用数据框。这样我们就可以像left_join 这样在excel 中进行映射(类似于vlookup)。

我们首先创建一个映射数据框:

df_region = data.frame(regions_numbers = c(2,9,21,142,150,419),
                      regions_names = c("Oceania", "Africa", "North America", "Asia", "Europe", "Latin America"))

现在,我们可以通过将任何未来向量转换为数据帧来进行映射:

new_region_numbers = data.frame(regions_numbers  = sample(c(2,9,21,142,150,419),10,replace = TRUE))

sample 只是给了我一组随机的region_numbers。现在通过left_join,我们很容易得到你想要的映射:

new_region_names =new_region_numbers %>% 
  left_join(df_region, by = c("regions_numbers" = "regions_numbers"))

带输出:

  regions_numbers regions_names
1              142          Asia
2              142          Asia
3              150        Europe
4                9        Africa
5              150        Europe
6              150        Europe
7               21 North America
8               21 North America
9              419 Latin America
10             150        Europe

如果您想要该矢量,则可以通过以下方式选择它:

new_names_only = new_region_names$regions_names 

这是一种方法。我确信有更多的“内置”功能来进行这些类型的映射。不过暂时想不出来。

【讨论】:

  • dplyr::recode() 也是如此。 Left Join 太冗长了。
【解决方案2】:

另一种简单的方式,整洁的方式......

sample_vec <- sample(regions_numbers, 20, replace = TRUE)
recode(sample_vec, "2" = "Oceania", "9" = "Africa", "21" = "North America",
           "142" = "Asia", "150" = "Europe", "419" = "Latin America")

有用link.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    • 1970-01-01
    • 2013-07-15
    • 1970-01-01
    • 2012-02-24
    相关资源
    最近更新 更多