将观察值从一个 Table 匹配到另一个 Table 由字符串组成的变量

Match Observation from One Table to Another Table Variable Consisting of Strings

我有两个数据集 A 和 B。

 library(data.table)
 Farm.Type <- c("Fruits","Vegetables","Livestock")
 Produce.All <- c("Apple, Orange, Pears, Strawberries","Broccoli, Cabbage, Spinach","Cow, Pig, Chicken")

 Store <- c("Convenience","Wholesale","Grocery","Market")
 Produce <- c("Oranges","Watermelon","Cabbage","Pig")
 Farm <- c("Fruits","","Vegetables","Livestock")

 A <- data.table(Farm.Type, Produce.All)
 B <- data.table(Store, Produce)

我正在尝试确定 Farm.Type table B 中的 Produce 在 table A 中属于什么,而不按顺序更改两个 table 的格式将 Farm.Type 字段拉入 table B. 这样数据框看起来像

 C <- data.table(Store, Produce, Farm)

我试过按以下方式使用 %in%:

 B$Farm[B$Produce %in% A$Produce.All] <- A$Farm.Type

但是因为A$Produce.All字段是带逗号的字符串,所以不匹配。

是否可以通过搜索字符串 (A$Produce.All) 来找到 B$Produce 的匹配项?

感谢任何帮助。

谢谢。

Farm.Type <- c("Fruits","Vegetables","Livestock")
Produce.All <- c("Apple, Oranges, Pears, Strawberries","Broccoli, Cabbage, Spinach","Cow, Pig, Chicken")

Store <- c("Convenience","Wholesale","Grocery","Market")
Produce <- c("Orange","Watermelon","Cabbage","Pig")
Farm <- c("Fruits","","Vegetables","Livestock")

这里不需要 data.table,所以我放弃使用它。你最好不要转换数据,因为你必须像这样进行旋转:

library(dplyr)
library(purrr)
library(stringi)

A <- data_frame(Farm.Type, Produce.All)
B <- data_frame(Store, Produce)

map(B$Produce, ~stri_detect_regex(A$Produce.All, sprintf("[[:space:],]*%s[[:space:],]*", .))) %>% 
  map(which) %>% 
  map_chr(~A$Farm.Type[ifelse(length(.)==0, NA, .)][1]) 

否则。 (您仍然需要将其添加到 B 数据框)

对比:

library(purrr)
library(dplyr)
library(tidyr)

mutate(A, Produce.All=stri_split_regex(Produce.All, ", ")) %>% 
  unnest(Produce.All) -> A_long

left_join(B, A_long, by=c("Produce"="Produce.All"))

而且,我当然希望这不是家庭作业。

模仿 hrbrmstr 的回答,但坚持使用 data.table 和一些基础 R:

longA <- 
  stack(
    setNames(
      strsplit(A[, Produce.All], ", "),
      A[, Farm.Type]
    )
  )

merge(longA, B, by.x = "values", by.y = "Produce", all.y = TRUE)
#      values        ind       Store
#1    Cabbage Vegetables     Grocery
#2    Oranges       <NA> Convenience
#3        Pig  Livestock      Market
#4 Watermelon       <NA>   Wholesale

# Or using a data.table merge, if you like
setDT(longA)[B, on = c(values = "Produce")]

当然,"Orange" 与 "Oranges," 不匹配,并且每个数据集中项目的复数和单数版本的不一致外观使合并更具挑战性。如果这也是需要做的事情,我建议在进行合并之前将复数版本映射到单数版本。