如何将一周中的天数转换为 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

以上是 如何将一周中的天数转换为 R 数据框列中的数字? 的全部内容, 来源链接: utcz.com/z/341290.html

回到顶部