2016-05-19 79 views
0

我真的會讚賞你的幫助。 我有一個ID表和列結果是touchpoint_type。 當ID與前一個不同時,我給「C」,如果不是「I」。 這是我的代碼: mydata_cce2 $ touchpoint_type < -C(O) mydata_cce2 $ touchpoint_type [1] = 「C」 J =長度(mydata_cce2 $ id_transaction) 爲(j在2:第(j-1)){R根據條件給出結果

if (mydata_cce2$id_transaction[j] != mydata_cce2$id_transaction[j-1]) 

    { mydata_cce2$touchpoint_type[j] ="C" 

    } 

    else { 

    mydata_cce2$touchpoint_type[j] = "I" 

    } 

} 
This is the results that I should get: 
id_transaction touchpoint_type 
    id_transaction touchpoint_type 
1 68013539 C 
2 68013539 I 
3 68013539 I 
4 68013702 C 
5 68013738 C 
6 68013738 I 

那單曲我得到的錯誤:錯誤:inesperado '}' 在 「}」

Blockquote

+2

R很不高興,你的格式很潦草。比較[這兩個if-else語句](https://gist.github.com/nathan-russell/1f1bf203496df6fd007e4751f7b81ff7#file-if-else-r)。 – nrussell

回答

0

你可以組合做一個ifelse()shift()

#Data 
df <- read.table(header=TRUE,text="id_transaction 
    68013539  
    68013539  
    68013539  
    68013702  
    68013738  
    68013738") 

library(data.table) 
df$touchpoint_type <- ifelse(shift(df$id_transaction,n=1L,type="lag") == df$id_transaction, "I","C") 

df 
    id_transaction touchpoint_type 
1  68013539   <NA> 
2  68013539    I 
3  68013539    I 
4  68013702    C 
5  68013738    C 
6  68013738    I 

注意,第一項是不是這個原因「C」,是因爲它在我的樣本數據幀中的第一項。如果上面有東西,它不會是NA。

+0

對不起MikeyMike,R說它找到了功能「轉移」。你爲什麼那樣?非常感謝 – JaviLarry

+0

它在'data.table'包中。我更新了我的代碼。對不包括這一點的道歉。 –

+0

非常感謝。它現在運作 – JaviLarry