繁体   English   中英

用R中另一个列表中的项目替换列表中的项目

[英]Replacing items in a list with items from another list in R

我在列表中有一列用字符表示的国家代码,我想用数字代码代替它们。 对于“解码”,我还有第二个列表,其中字符国家/地区代码与数字代码相关联。

我试过gsub:

   for (i in 1:nrow(countries))
{gsub(countries$code3[i], countries$numcode[i], doc_report$nationality)}

我尝试了for循环:

i <- NULL
n <- NULL
for (i in 1:nrow(doc_report)) {
  for (n in 1:nrow(countries)) {
    if(doc_report$nationality[i] == countries$code3[n])
      doc_report$nationality[i] <- countries$numcode[n]
    else
      if(doc_report$nationality[i] == "NA")
      doc_report$nationality[i] <- 000
  }
}

我对merge()有一些想法

这就是必须替换该列的样子

[nationality] IRL GBR ITA FRA POL BRA ESP GBR GBR GBR

这是第二张解码表的样子:

 [code3] AFG ALB DZA ASM AGO AIA     ATG ARG ARM
 [numcode]   4   8  12  16  24 660  NA  28  32  51

所以在表一中,我想要表2中的数字代码,而不是code3样式。

更新的答案

这是一个示例,其数据格式与您的数据类似,以使您清楚地知道,即使国家/地区代码重复,它也可以正常工作。

library(tidyverse)
country <- c("IRL", "GBR", "ITA", "FRA", "POL", "BRA", "ESP")
codes <- c(1,2,3,4,5,6,7)
countries <- tibble(country, codes)

doc_report <- tibble(x=c("a","b","c","d","e"),
           country = c("ITA","ITA", "POL", "BRA","ESP"))

left_join(doc_report, countries, by="country")

此代码的输出是:

# A tibble: 5 x 3
  x     country codes
  <chr> <chr>   <dbl>
1 a     ITA         3
2 b     ITA         3
3 c     POL         5
4 d     BRA         6
5 e     ESP         7

我相信这是您要寻找的行为。

原始答案

一个简单的解决方案是使用dplyr包中的left_join()函数,然后使用select()删除不需要的列。

假设doc_report通过代码对国家/ doc_report关键字设置,并且country_codes是带有1列国家/地区字符串代码和1列相应数字代码的doc_report ,您可以执行以下操作

## join the country codes
doc_report <- left_join(doc_report, country_codes, by="code3")
## remove the unneeded column
doc_report <- select(doc_report, -code3)

这有意义吗? 乐于扩展。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM