gpt4 book ai didi

r - 如何直方图星期几,并有字符串标签

转载 作者:行者123 更新时间:2023-12-04 10:46:25 25 4
gpt4 key购买 nike

我有一个日期数据框(Date 对象);见底部。
我试图将它们转换为星期几,然后绘制直方图,但理想情况下,标签是“星期一”...“星期日”(不是数字)

我有两个不同的问题:

  • 很简单to convert a Date object to day-of-week ,但结果是字符串或数字,而不是对象。
  • 当我得到直方图时,箱和标签是错误的(见下文)。

  • 如果我使用 weekdays(dat) , 输出是字符串 ("Monday"...) 不能用于 hist() .

    或者,如果我转换为数字数据,如何在 hist() 上获取字符串标签?
    > dotw <- with( month.day.year(dat[,1]), day.of.week(month,day,year) )
    > hist(xxx,labels=c('M','Tu','W','Th','F','Sa','Su'),col='black') # WTF?!
    > hist(dotw,xlab=list('M','Tu','W','Th','F','Sa','Su'))

    无法按预期进行标记。 0.5 宽度的垃圾箱有什么用?而且,如何防止周日-> 0 和周一-> 1 之间缺少间隙?理想情况下,列之间没有间隙。

    我的数据看起来像:
    > dat
    [1] "2010-04-02" "2010-04-06" "2010-04-09" "2010-04-10" "2010-04-14" "2010-04-15" "2010-04-19"
    [8] "2010-04-21" "2010-04-22" "2010-04-23" "2010-04-26" "2010-04-28" "2010-04-29" "2010-04-30"
    ...

    > str(dat)
    Date[1:146], format: "2010-04-02" "2010-04-06" "2010-04-09" "2010-04-10" "2010-04-14" "2010-04-15" ...

    > str(weekdays(dat))
    chr [1:146] "Friday" "Tuesday" "Friday" "Saturday" "Wednesday" "Thursday" "Monday" ...
    > hist(weekdays(dat))
    Error in hist.default(weekdays(dat)) : 'x' must be numeric

    最佳答案

    dat <- as.Date( c("2010-04-02", "2010-04-06", "2010-04-09", "2010-04-10", "2010-04-14", 
    "2010-04-15", "2010-04-19", "2010-04-21", "2010-04-22", "2010-04-23","2010-04-24",
    "2010-04-25", "2010-04-26", "2010-04-28", "2010-04-29", "2010-04-30"))
    dwka <- format(dat , "%a")
    dwka
    # [1] "Fri" "Tue" "Fri" "Sat" "Wed" "Thu" "Mon"
    # [8] "Wed" "Thu" "Fri" "Sat" "Sun" "Mon" "Wed"
    # [15] "Thu" "Fri"
    dwkn <- as.numeric( format(dat , "%w") ) # numeric version
    hist( dwkn , breaks= -.5+0:7, labels= unique(dwka[order(dwkn)]))

    enter image description here

    关于r - 如何直方图星期几,并有字符串标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6923223/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com