2013-11-27 38 views
0

我有,我已經使用了以下基本命令加載爲R .csv文件:直方圖平日的按年[R

lace <- read.csv("lace for R.csv")

它在拉我的數據就好了。下面是數據的str

str(lace) 
'data.frame': 2054 obs. of 20 variables: 
$ Admission.Day  : Factor w/ 872 levels "1/1/2013","1/10/2011",..: 231 238 238 50 59 64 64 64 67 67 ... 
$ Year    : int 2010 2010 2010 2011 2011 2011 2011 2011 2011 2011 ... 
$ Month    : int 12 12 12 1 1 1 1 1 1 1 ... 
$ Day     : int 28 30 30 3 4 6 6 6 7 7 ... 
$ DayOfWeekNumber  : int 3 5 5 2 3 5 5 5 6 6 ... 
$ Day.of.Week   : Factor w/ 7 levels "Friday","Monday",..: 6 5 5 2 6 5 5 5 1 1 ... 

我所試圖做的是創造三(3)不同的直方圖,然後繪製它們放在一起的一個。我想爲每年創建一個直方圖,其中x軸或標籤將是從週日開始到週六結束的一週中的某幾天。

首先,我該如何去創建一個直方圖,因爲一週中的日子在哪裏?

其次我如何創建一個給定年份的星期幾直方圖?

我已經嘗試使用以下文章here,但無法使其工作。我用的是Admission.Day作爲變量,並得到一個錯誤信息:

dat <- as.Date(lace$Admission.Day)

Error in charToDate(x) : character string is not in a standard unambiguous format

謝謝

+1

你需要做的第一件事就是閱讀文檔'as.Date',特別是爲說明?格式參數。接下來,您將需要查看「?weekdays」函數。 – joran

+1

'as.Date'需要一個來源'dat < - as.Date(lace $ Admission.Day,origin =「1970-01-01」)' –

+0

@joran現在就得到所有的日期,謝謝你指出格式部分,沒有一個由excel指定的起源,實際上是把所有東西都拋棄了。 –

回答

1

擴展在上面的評論:這個問題似乎是與進口日期,而比製作​​直方圖。假設有一個excel工作簿「R.xlsx花邊」,帶有一個「花邊」工作表:

## Not tested... 
library(XLConnect) 
myData <- "lace for R.xlsx"    # NOTE: need path also... 
wb  <- loadWorkbook(myData) 
lace <- readWorksheet(wb, sheet="lace") 
lace$Admission.Day <- as.Date(lace$Admission.Day) 

應提供適用於所有R日期函數的日期。此外,lubridate軟件包提供了許多比format(...)更直觀的功能。

那麼,作爲一個例子:

library(lubridate) # for year(...) and wday(...) 
library(ggplot2) 
# random dates around Jun 1, across 5 years... 
set.seed(123) 
lace <- data.frame(date=as.Date(rnorm(1000,sd=50)+365*(0:4),origin="2008/6/1")) 
lace$year <- factor(year(lace$date)) 
lace$dow <- wday(lace$date, label=T) 
# This creates the histograms... 
ggplot(lace) + 
    geom_histogram(aes(x=dow, fill=year)) +  # fill color by year 
    facet_grid(~year) +       # facet by year 
    theme(axis.text.x=element_text(angle=90)) # to rotate weekday names... 

產生以下: enter image description here

+0

非常有幫助謝謝 –