2014-06-15 67 views
0

我在處理R中的某些數據時遇到了問題。我有一個包含信息的數據框。與客戶交易有關。我提取最小日期如下,R日期/列表問題

hold <- (lapply(with(train_train, split(date,id)),min)) # minimum date 

給我下面的列表:

head(hold) 

#$`15994113` 
#[1] "2012-03-02" 
# 
#$`16203579` 
#[1] "2012-03-02" 
# 
#$`17472223` 
#[1] "2012-03-22" 

我則想要做的就是採取返回每個ID的日期,並把它合併到數據包含每個id的其他相關變量的框架。我試圖這樣做:

hold <- as.data.frame(unlist(hold)) 
hold <- as.data.frame(cbind(row.names(hold),hold[,1])) 
names(hold) <- c('id', 'mindate') 
transactions.temp <- merge(x = transactions.pro, y = hold, by = 'id') 

但是,綁定破壞的日期格式,我無法工作,如何讓'身份證「MINDATE」,使我這個合併到我的主數據集,看起來像這樣的數據結構;

> head(transactions.pro) 
      id totaltransactions totalspend  meanspend 
1: 100007447    1096 6644.88 6.06284671532847 
2: 100017875    348  992.29 2.85140804597701 
3: 100051423    646 2771.43 4.29013931888545 
4: 1000714152    2370 10509.08 4.43421097046414 
5: 1002116097    1233 4158.51 3.37267639902676 
6: 1004404618    754 2978.15 3.94980106100796 

您提供的任何建議將非常感激。謝謝!

回答

1

cbind被隱式日期轉換爲character因爲row.names。爲cbind使用data.frame方法來實現此目的。從本質上取代:

as.data.frame(cbind(row.names(hold),hold[,1])) 

cbind.data.frame(row.names(hold), hold[,1]) 
1

你可以嘗試用dplyr,採用不同的方法,你就不會轉換到一個列表,但保持mindate S作爲data.frame然後left_join(= mergeall.x=TRUE)它的transactions.pro data.frame。由於沒有可重複的例子,我沒有測試它。

require(dplyr) 

train_train %>% 
    mutate(date = as.Date(as.character(date))) %>% 
    group_by(id) %>% 
    summarize(mindate = min(date)) %>% 
    left_join(transactions.pro, ., by = "id")