2017-04-18 76 views
0

在我的劇本我已經改變這個data.frame如圖所示:[R修改類DIFFTIME到HIST

df.modified<-transform(df, new.col= Payment.date-Selectionfinal$Invoice.Date) 

這是結果:

Client.Code. Invoice.Date Payment.date new.col 
1:  1004850 2016-01-31 2016-11-22 296 days 
2:  1004850 2016-06-30 2016-11-22 145 days 
3:  1004850 2016-06-30 2016-11-22 145 days 
4:  1004850 2016-06-30 2016-11-22 145 days 
5:  1004850 2016-09-30 2016-11-22 53 days 

然後,我需要把它繪製成一個直方圖,但我有這樣的問題:

> hist(df.modified[,c(4)]) 
Error in hist.default(Completo[, c(4)]) : 'x' must be numeric 

這是我的DF的STR:

$ Client.Code.: int 1004850 1004850 1004850 1004850 1004850 1004850 1004850 1004874 1004874 1005133 ... 
$ Invoice.Date: Date, format: "2016-01-31" "2016-06-30" "2016-06-30" "2016-06-30" ... 
$ Payment.date: Date, format: "2016-11-22" "2016-11-22" "2016-11-22" "2016-11-22" ... 
$ new.col  :Class 'difftime' atomic [1:4430] 296 145 145 145 53 53 53 102 72 71 ... 

請我想知道這個技巧。謝謝。

+1

'HIST(as.numeric(df.modified [,C(4)]))' – Kristofersen

+0

我嘗試這樣做之前:(> HIST(as.numeric(df.modified [,C(4)] )) 錯誤在hist(as.numeric(df.modified [,c(4)])): (list)object can not be coerced to type'double') –

+0

@ÁlvaroRodríguez您是否還需要針對此問題的解決方案? – KoenV

回答

0

正如Kristofersen已經指出的那樣,問題在於你將數據傳遞給hist函數的類型。數據預計爲numeric,不接受difftime

# some data mimicking your data 
Client.Code. <- c(1004850, 1004849, 1004850, 1004850, 1004851) 
Invoice.Date <- as.Date(c("2016-01-31", "2016-03-30", "2016-06-30", "2016-06-30", "2016-04-30")) 
Payment.date <- as.Date(c("2016-11-22", "2016-10-22", "2016-09-22", "2016-08-22", "2016-10-09")) 
# creating the new column in a similar way to your way 
df <- data.frame(Client.Code., Invoice.Date, Payment.date) 
df$new.col <- df$Payment.date - df$Invoice.Date 

## the following 3 do not work because they pass difftime to hist() 
hist(df[,c(4)]) 
hist(df[,4]) 
hist(df$new.col) 

# class of difftime 
class(df$new.col) 

## these 3 do work: numeric is passed to hist() 
hist(as.numeric(df$new.col)) 
hist(as.numeric(df[,4])) 
hist(as.numeric(df[,c(4)])) 
+0

HI,KoenV,正如我之前所說的,我已經在問題之前試過了這個: –

+0

嗨,Alvaro,我已經運行並測試了我的代碼。這對我來說可以。 – KoenV