2017-12-29 18 views
0

私はさまざまな国のブロードバンドデータのデータフレームを持っています(たとえば、AT_dfを取る)。 「ofWithTV」および「ofWithFT」の列は文字型であり、それぞれのケース(ブロードバンドオファー)にバンドルされたTVアクセスまたは固定テレフォニーアクセスが付属しているかどうかを示します。私はそのような場合は、両方のイベントは、イベントが「はい」とされている「いいえ」、「テレビDoubleplay」ある「Singleplay」と呼ばれるものと新しい列「ofProduct」を作成したい文字列値でデータフレームの新しい列を埋める論理演算

ofWithTV ofWithFT 
no   no 
no   no 
no   no 
yes   no 
yes   no 
no   no 
no   yes 
no   yes 
no   yes 
no   yes 
yes   yes 
yes   yes 

。 「いいえ」、「FT Doubleplay」はイベントが「いいえ」、両方のイベントが「はい」の場合は「はい」および「トリプルプレイ」。このような何か:このため

ofWithTV ofWithFT ofProduct 
no   no   Singleplay 
no   no   Singleplay 
no   no   Singleplay 
yes   no   TV Doubleplay 
yes   no   TV Doubleplay 
no   no   Singleplay 
no   yes  FT Doubleplay 
no   yes  FT Doubleplay 
no   yes  FT Doubleplay 
no   yes  FT Doubleplay 
yes   yes  Tripleplay 
yes   yes  Tripleplay 

、私は既存のデータを上書き/削除せずに新しい値「Singelplay、Doubleplayを、...」を割り当てるために論理演算を必要としています。私はすでに同様のものを探しましたが、実際にどのように動作しているかを見つける/理解できません。

私はこのコミュニティで初めて、R(最初の投稿)の新機能です。誰かが助けることを願っています。

答えて

1

case_whenから使用できます。

library(dplyr) 

dat2 <- dat %>% 
    mutate(ofProduct = case_when(
    ofWithTV %in% "no" & ofWithFT %in% "no" ~ "Singleplay", 
    ofWithTV %in% "yes" & ofWithFT %in% "no" ~ "TV Doubleplay", 
    ofWithTV %in% "no" & ofWithFT %in% "yes" ~ "FT Doubleplay", 
    ofWithTV %in% "yes" & ofWithFT %in% "yes" ~ "Tripleplay" 
)) 
dat2 
# ofWithTV ofWithFT  ofProduct 
# 1  no  no Singleplay 
# 2  no  no Singleplay 
# 3  no  no Singleplay 
# 4  yes  no TV Doubleplay 
# 5  yes  no TV Doubleplay 
# 6  no  no Singleplay 
# 7  no  yes FT Doubleplay 
# 8  no  yes FT Doubleplay 
# 9  no  yes FT Doubleplay 
# 10  no  yes FT Doubleplay 
# 11  yes  yes Tripleplay 
# 12  yes  yes Tripleplay 

または、ルックアップテーブルを作成してから、テーブルを元のデータフレームに結合することができます。

library(dplyr) 
library(tibble) 

look_up <- tribble(
    ~ofWithTV, ~ofWithFT, ~ofProduct, 
    "no"  , "no"  , "Singleplay", 
    "yes" , "no"  , "TV Doubleplay", 
    "no"  , "yes" , "FT Doubleplay", 
    "yes" , "yes" , "Tripleplay" 
) 

dat3 <- dat %>% 
    left_join(look_up, by = c('ofWithTV', "ofWithFT")) 
dat3 
# ofWithTV ofWithFT  ofProduct 
# 1  no  no Singleplay 
# 2  no  no Singleplay 
# 3  no  no Singleplay 
# 4  yes  no TV Doubleplay 
# 5  yes  no TV Doubleplay 
# 6  no  no Singleplay 
# 7  no  yes FT Doubleplay 
# 8  no  yes FT Doubleplay 
# 9  no  yes FT Doubleplay 
# 10  no  yes FT Doubleplay 
# 11  yes  yes Tripleplay 
# 12  yes  yes Tripleplay 

DATA

dat <- read.table(text = "ofWithTV ofWithFT 
no   no 
no   no 
no   no 
yes   no 
yes   no 
no   no 
no   yes 
no   yes 
no   yes 
no   yes 
yes   yes 
yes   yes", 
        header = TRUE, stringsAsFactors = FALSE) 
+1

どうもありがとう!完璧に働いた – Luke666