【问题标题】:Match and copy column based in one column and partial match of another column基于一列的匹配和复制列以及另一列的部分匹配
【发布时间】:2019-05-02 10:06:36
【问题描述】:

我有两个数据框。

数据

Name                Type            Code
gabapentine         Pharmaceutical  60142-96-3
Glyphosate          Pesticide       1071-83-6
Guanylurea          Pharmaceutical  141-83-3
hydrochlorthiazide  Pharmaceutical  58-93-5

价值观

Name                Value           Code
gabapentine         0,2             60142-96-3
Glyphosate          1,8             1071-83-6
Urea                1,2             141-83-3
hydrochlorthiazide  0,5             58-93-5

我想通过匹配列 NameCode 将列 typeData 添加到 Values

我知道如何只匹配一列,如下所示:

Values$type = Data$type[match(Values$Name, Data$Name)]

但现在我还想考虑Code,因为有些名字不匹配。

有没有办法在一行中做到这一点,比如

Values$type = Data$type[match((Values$Name, Data$Name) | (Values$Code, Data$Code))]

这对我不起作用,所以我想知道正确的方法。

我尝试像其他问题一样使用合并

merge(Values, Data,all.x = TRUE)

但是在来自数据帧DataGuanylurea 中,当它应该与来自数据帧ValuesUrea 匹配时,我会得到类型NA。该行的结果将是Type 等于Pharmaceutical,但Names 不完全匹配。那么如何将部分匹配添加到函数matchmerge 中?或者这两个有替代品吗?

【问题讨论】:

  • merge(Values, Data,all.x = TRUE)
  • 我试过了,但在 Guanyurea 中,我得到的是 NA 类型而不是 Pharmaceutical,可能是因为名称不完全匹配。

标签: r dataframe match


【解决方案1】:

对此有多种答案。我留下了四个 (dfrx),都使用 dplyr。

library(dplyr)
df1 <- data.frame(Name = c("gabapentine", "Glyphosate",
                           "Guanylurea", "hydrochlorthiazide"),
                  Type = c("Pharmaceutical", "Pesticide", 
                           "Pharmaceutical", "Pharmaceutical"),
                  Code = c("60142-96-3", "1071-83-6",
                           "141-83-3", "58-93-5"))
df2 <- data.frame(Name = c("gabapentine", "Glyphosate",
                           "Guanylurea", "hydrochlorthiazide"),
                  Value = c(0.2, 1.8, 1.2, 0.5),
                  Code = c("60142-96-3", "1071-83-6",
                           "141-83-3", "58-93-5"))

dfr1 <- df2 %>% 
  dplyr::mutate(Type = df1$Type)
dfr2 <- df2 %>% 
  dplyr::bind_cols(Type = df1$Type)
dfr3 <- df2 %>% 
  dplyr::right_join(df1, by = "Name") %>% 
  dplyr::select(-Code.y) %>% 
  dplyr::rename("Code" = Code.x)
dfr4 <- df2 %>% 
  dplyr::right_join(df1, by = "Code") %>% 
  dplyr::select(-Name.y) %>% 
  dplyr::rename("Name" = Name.x)
> dfr4
                Name Value       Code           Type
1        gabapentine   0.2 60142-96-3 Pharmaceutical
2         Glyphosate   1.8  1071-83-6      Pesticide
3         Guanylurea   1.2   141-83-3 Pharmaceutical
4 hydrochlorthiazide   0.5    58-93-5 Pharmaceutical

【讨论】:

    猜你喜欢
    • 2019-11-29
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 2021-03-28
    • 2018-02-18
    • 2016-08-05
    相关资源
    最近更新 更多