名や食材のすべての組み合わせが必要なrecipee
dtf2 <- dtf %>%
# say that it's present in the list
mutate(present = 1) %>%
full_join(desiredrecipe, by = c("Name","Inventory")) %>%
group_by(Name) %>%
mutate(BLT_Flag = ifelse(sum(present)==numberofingredients,1,0))
# replace NA values by 0
dtf2$BLT_Flag[is.na(dtf2$BLT_Flag)] <- 0
dtf2
# Name Inventory present BLT_Flag
# <chr> <chr> <dbl> <dbl>
# 1 Amy Bacon 1 1
# 2 Amy Lettuce 1 1
# 3 Amy Tomato 1 1
# 4 John Bacon 1 0
# 5 John Tomato 1 0
# 6 Katie Bacon 1 1
# 7 Katie Lettuce 1 1
# 8 Katie Tomato 1 1
# 9 John Lettuce NA 0
に存在している場合は希望recipee
desiredrecipe <- expand.grid(Inventory = c("Bacon", "Lettuce", "Tomato"),
Name = unique(dtf$Name),
stringsAsFactors = FALSE)
numberofingredients <- length(unique(desiredrecipe$Inventory))
確認のため名前や食材のすべての組み合わせを生成するデータ
library(dplyr)
dtf <- read.table(text = "Name Inventory
Amy Bacon
Amy Lettuce
Amy Tomato
John Bacon
John Tomato
Katie Bacon
Katie Lettuce
Katie Tomato ", header = TRUE, stringsAsFactors = FALSE)
を作成します。
再現可能な例は非常に高く評価されるでしょう。 http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – snoram
前の例を間違って入力しました。私は上記の表がより理にかなっていることを願う。 – mrp
行が重複している可能性がありますか、または特定の名前が3回現れて「BLT = 1」と表示される場合はありますか? – snoram