2017-02-28 2 views
0

現在、Rのデータフレームに列を追加しようとしていますが、特定の条件が満たされている場合は3番目の列にフラグが設定されます。下のサンプルデータセットを見てください。Rの列の値を他の場合に比較して3番目の列を埋める

Name | Inventory | BLT_Flag 
Amy Bacon  1 
Amy lettuce  1 
Amy Tomato  1 
John Bacon  0 
John Tomato  0 
Katie Bacon  1 
Katie Lettuce  1 
Katie Tomato  1 

基本的に、私はBLT_Flagをコード化しようとしています。この例では、AmyとKatieの両方がBLT Flagsを取得しています。その理由は、在庫にBLTのすべての成分が含まれていて、Johnには「Lettuce」がないからです。私はこのフラグを作成するためのループを作成するのに苦労しています。どんな提案も大歓迎です!

+0

再現可能な例は非常に高く評価されるでしょう。 http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – snoram

+1

前の例を間違って入力しました。私は上記の表がより理にかなっていることを願う。 – mrp

+0

行が重複している可能性がありますか、または特定の名前が3回現れて「BLT = 1」と表示される場合はありますか? – snoram

答えて

1

名前に という名前が3回出現する場合、BLT_Flagは1である必要があります。 の数がカウントされ、3であるかどうかテストできます。
名前に基づいて各行のBLT_Flagを構築します。 私はあなたのデータをSuppliesという名前のdata.frameに保存しました。

SupplyTable = table(Supplies$Name) == 3 
SupplyTable 
    Amy John Katie 
TRUE FALSE TRUE 

BLT_Flag = as.numeric(SupplyTable[Supplies$Name]) 
BLT_Flag 
[1] 1 1 1 0 0 1 1 1 

しかし、@Sotosが指摘しているように、この解決策はこの問題に非常に特有です。もっと一般的な解決策は、成分のリストを提供し、各名前に利用可能なすべての成分であるかどうかをテストすることです。それはで実現することができます。前と同じように

IngredientList = c("Bacon", "Tomato", "Lettuce") 
SupplyTable = sapply(unique(Supplies$Name), 
    function(x) sum(!is.na(match(IngredientList, 
     Supplies$Inventory[Supplies$Name == x]))) == length(IngredientList)) 
SupplyTable 
    Amy John Katie 
TRUE FALSE TRUE 

AllIngredientsFlag = as.numeric(SupplyTable[Supplies$Name]) 
AllIngredientsFlag 
[1] 1 1 1 0 0 1 1 1 

、私たちは旗を作成するためにそれを使用し、その後、すべての成分が存在するかどうかを名前ごとに示すテーブルを生成します。

+0

申し訳ありません...全く別のものを考えていました。私はベーコン、トマト、チーズのコンボを考えていましたが、もう一度私は空腹です:) – Sotos

+0

OPのリクエストはBTCではなくBLTに対するものでした。あなたはそれについて新しい質問を開くべきです。 – G5W

+0

それにもかかわらず、あなたのソリューションは十分に一般的ではありません。 – Sotos

0

名や食材のすべての組み合わせが必要な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) 

を作成します。

関連する問題