我无法将工作日的.csv数据列转换为数字(因此1 =星期一,2 =星期二,3 =星期三等)。我正在尝试使用 strptime 功能,如下所示:http://www.inside-r.org/r-doc/base/strftime
由于我想将工作日转换为数字,我使用了“%u”格式化选项。这是我的代码:
> newweekdaynum <- strptime(SFCrimeData$DayOfWeek, "%u")
其中SFCrimeData是一个拥有大量犯罪信息的数据集。在我运行语句后没有出现错误,但是当我想打印“newweekdaynum”时,所有出现的都是一个巨大的值表,都是“NA”。
我做错了什么?
答案 0 :(得分:7)
strptime
。它将返回一个datetime对象。那不是你想要的。
相反,您可以使用有序因子:
#some example data
set.seed(42)
x <- factor(sample(c("Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"),
20, TRUE))
# [1] Sunday Sunday Wednesday Saturday Friday Thursday Saturday Monday Friday Friday Thursday Saturday Sunday
#[14] Tuesday Thursday Sunday Sunday Monday Thursday Thursday
#Levels: Friday Monday Saturday Sunday Thursday Tuesday Wednesday
#turn into ordered factor
x <- factor(x, levels = c("Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"),
ordered = TRUE)
#[1] Sunday Sunday Wednesday Saturday Friday Thursday Saturday Monday Friday Friday Thursday Saturday Sunday
#[14] Tuesday Thursday Sunday Sunday Monday Thursday Thursday
#Levels: Monday < Tuesday < Wednesday < Thursday < Friday < Saturday < Sunday
#extract underlying integer values
as.integer(x)
#[1] 7 7 3 6 5 4 6 1 5 5 4 6 7 2 4 7 7 1 4 4
(你真的不需要把它作为有序因子,以正确顺序指定的水平就足够了,但工作日在概念上是一个有序因子。)
答案 1 :(得分:0)
df$Date <- as.Date(df$Date)
df$wkdaynum <- format(df$Date,"%u")
df$wkdaynum <- as.numeric(df$wkdaynum)
因此,您的错误是使用strptime()而不是format()。