如何在 R 数据框列中将一周中的日期转换为数字?


为了将 R 数据框列中的一周中的日期转换为数字,我们需要通过定义工作日作为级别将该列转换为因子,然后将该列读取为整数。

如果我们在转换过程中提供了正确的工作日顺序,则星期一将转换为 1。查看下面的示例以了解如何操作。

示例 1

以下代码片段创建了一个示例数据框 -

Week_Days<-
sample(c("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"),20,replace=TRUE)
df1<-data.frame(Week_Days)
df1

创建了以下数据框

   Week_Days
1     Friday
2     Monday
3    Tuesday
4   Saturday
5   Thursday
6    Tuesday
7     Monday
8   Thursday
9   Thursday
10    Friday
11  Thursday
12    Sunday
13  Thursday
14   Tuesday
15 Wednesday
16    Sunday
17    Friday
18 Wednesday
19    Sunday
20  Thursday

要将 df1 中的 Week_Days 转换为数字并在上面创建的数据框的不同列中读取它们,请将以下代码添加到上面的代码片段中 -

Week_Days<-
sample(c("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"),20,replace=TRUE)
df1<-data.frame(Week_Days)
df1$Days_Number<-
as.integer(factor(df1$Week_Days,levels=c("Monday","Tuesday","Wednesday","Thursd
ay","Friday","Saturday","Sunday"),ordered=TRUE))
df1

创建了以下数据框

  Week_Days  Days_Number
1     Friday          5
2     Monday          1
3    Tuesday          2
4   Saturday          6
5   Thursday          4
6    Tuesday          2
7     Monday          1
8   Thursday          4
9   Thursday          4
10    Friday          5
11  Thursday          4
12    Sunday          7
13  Thursday          4
14   Tuesday          2
15 Wednesday          3
16    Sunday          7
17    Friday          5
18 Wednesday          3
19    Sunday          7
20  Thursday          4

示例 2

以下代码片段创建了一个示例数据框 -

Time<-
sample(c("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"),20,replace=TRUE)
df2<-data.frame(Time)
df2

创建了以下数据框

       Time
1    Tuesday
2   Thursday
3     Monday
4    Tuesday
5   Thursday
6     Sunday
7   Saturday
8     Monday
9   Thursday
10  Saturday
11 Wednesday
12    Monday
13 Wednesday
14    Sunday
15    Sunday
16    Sunday
17    Sunday
18 Wednesday
19  Saturday
20    Friday

要将 df2 中的时间转换为数字并在上面创建的数据框的不同列中读取它们,请将以下代码添加到上面的代码片段中 -

Time<-
sample(c("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"),20,replace=TRUE)
df2<-data.frame(Time)
df2$Day_Number<-
as.integer(factor(df2$Time,levels=c("Monday","Tuesday","Wednesday","Thursday","
Friday","Saturday","Sunday"),ordered=TRUE))
df2

输出

如果您将以上所有给定的代码片段作为单个程序执行,它将生成以下输出 -

       Time Day_Number
1    Tuesday        2
2   Thursday        4
3     Monday        1
4    Tuesday        2
5   Thursday        4
6     Sunday        7
7   Saturday        6
8     Monday        1
9   Thursday        4
10  Saturday        6
11 Wednesday        3
12    Monday        1
13 Wednesday        3
14    Sunday        7
15    Sunday        7
16    Sunday        7
17    Sunday        7
18 Wednesday        3
19  Saturday        6
20    Friday        5

更新于: 2021-11-01

1K+ 阅读量

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告