2017-08-21 42 views
1

這是我的數據幀的樣子: 的一首歌門戶網站的數據(如iTunes或raaga)查找基於發生的「罕見」的用戶在兩列

datf <- read.csv(text = 
"albumid,date_transaction,listened_time_secs,userid,songid 
6263,3/28/2017,59,3747,6263 
3691,4/24/2017,53,2417,3691 
2222,3/24/2017,34,2417,9856 
1924,3/16/2017,19,8514,1924 
6691,1/1/2017,50,2186,6691 
5195,1/1/2017,64,2186,5195 
2179,1/1/2017,37,2186,2179 
6652,1/11/2017,33,1145,6652") 

我的目標是挑選淘汰罕見的用戶。 「罕見」用戶是每個日曆月訪問門戶不超過一次的用戶。

例如:2186並不少見。 2417是罕見的,因爲它在2月差異只發生一次,所以是3747,1145和8514.

我一直是這樣的:

DuplicateUsers <- duplicated(songsdata[,2:4]) 
DuplicateUsers <- songsdata[DuplicateUsers,] 


DistinctSongs <- songsdata %>% 
    distinct(sessionid, date_transaction, .keep_all = TRUE) 

RareUsers <- anti_join(DistinctSongs, DuplicateUsers, by='sessionid') 

但似乎並沒有工作。

回答

1

使用library(dplyr)你可以這樣做:

# make a new monthid variable to group_by() with 
songdata$month_id <- gsub("\\/.*", "", songdata$date_transaction) 

RareUsers <- group_by(songdata, userid, month_id) %>% 
    filter(n() == 1) 

RareUsers 
# A tibble: 5 x 6 
# Groups: userid, month_id [5] 
    albumid date_transaction listened_time_secs userid songid month_id 
    <int>   <chr>    <int> <int> <int> <chr> 
1 6263  3/28/2017     59 3747 6263  3 
2 3691  4/24/2017     53 2417 3691  4 
3 2222  3/24/2017     34 2417 9856  3 
4 1924  3/16/2017     19 8514 1924  3 
5 6652  1/11/2017     33 1145 6652  1 
1

你可以嘗試這樣的:

df %>% 
    mutate(mth = lubridate::month(mdy(date_transaction))) %>% 
    group_by(mth, userid) %>% 
    filter(n() == 1) 

這給:

albumid date_transaction listened_time_secs userid songid mth 
    <int>   <fctr>    <int> <int> <int> <dbl> 
1 6263  3/28/2017     59 3747 6263  3 
2 3691  4/24/2017     53 2417 3691  4 
3 2222  3/24/2017     34 2417 9856  3 
4 1924  3/16/2017     19 8514 1924  3 
5 6652  1/11/2017     33 1145 6652  1 
0

你可以用基礎R做到這一點:

# parse date and extract month 
datf$date_transaction <- as.Date(datf$date_transaction, "%m/%d/%Y") 
datf$month <- format(datf$date_transaction, "%m") 

# find non-duplicated pairs of userid and month 
aux <- datf[, c("userid", "month")] 
RareUsers <- setdiff(aux, aux[duplicated(aux), ]) 
RareUsers 
# userid month 
# 1 3747 03 
# 2 2417 04 
# 3 2417 03 
# 4 8514 03 
# 5 1145 01 

如果您需要其他欄目:

merge(RareUsers, datf) 
# userid month albumid date_transaction listened_time_secs songid 
# 1 1145 01 6652  2017-01-11     33 6652 
# 2 2417 03 2222  2017-03-24     34 9856 
# 3 2417 04 3691  2017-04-24     53 3691 
# 4 3747 03 6263  2017-03-28     59 6263 
# 5 8514 03 1924  2017-03-16     19 1924