如何检查 R 中的类别是否匹配,其中类别存储在不同的文件中并且一个元素可以有多个类别?
How do I check if category matches in R where the category is stored in a different file and an element can have multiple categories?
我有两个表,Catdata 和 ElementData。如果 Catdata$category
是 fiction
或 suspense
或 thriller
,我希望 ElementData$Match
到 return 1,否则为 0。如果不循环,我将如何做到这一点?
大数据
Element Category
abc123 thriller
abc123 horror
def456 fiction
def456 suspense
def456 thriller
pqr789 romance
pqr789 fiction
xyz123 thriller
元素数据
Element Match
def456
abc123
xyz123
pqr789
If you want ElementData$Match
to return 1 if any value of Catdata$category
for the corresponding value of Catdata$Element
matches条件,您可以执行以下操作:
library(dplyr)
## Create lookup table of all elements matching the criteria:
matchData <- Catdata %>%
group_by(Element) %>%
dplyr::summarise(Match = (Category %in%
c("fiction", "suspense", "thriller")) %>%
any %>% as.integer)
## Merge your second table with the lookup table
ElementData <- ElementData %>% left_join(matchData, by = "Element")
我有两个表,Catdata 和 ElementData。如果 Catdata$category
是 fiction
或 suspense
或 thriller
,我希望 ElementData$Match
到 return 1,否则为 0。如果不循环,我将如何做到这一点?
大数据
Element Category
abc123 thriller
abc123 horror
def456 fiction
def456 suspense
def456 thriller
pqr789 romance
pqr789 fiction
xyz123 thriller
元素数据
Element Match
def456
abc123
xyz123
pqr789
If you want ElementData$Match
to return 1 if any value of Catdata$category
for the corresponding value of Catdata$Element
matches条件,您可以执行以下操作:
library(dplyr)
## Create lookup table of all elements matching the criteria:
matchData <- Catdata %>%
group_by(Element) %>%
dplyr::summarise(Match = (Category %in%
c("fiction", "suspense", "thriller")) %>%
any %>% as.integer)
## Merge your second table with the lookup table
ElementData <- ElementData %>% left_join(matchData, by = "Element")