我有一个数据框中的一列包含星期几的数字(从0到6,0代表星期天,1代表星期一等),我需要将其转换为星期几的名称。如何做到这一点呢?
示例数据:
df <- data.frame(day_number=0:6)
dplyr的简单用法。
library(dplyr)
df <- data.frame(day_number=0:6)
df$day_number <- recode(df$day_number,
"0"="Sunday",
"1"="Monday",
"2"="Tuesday",
"3"="Wednesday",
"4"="Thursday",
"5"="Friday",
"6"="Saturday")
lubridate
中实现此操作。 lubridate
将星期几编码为1至7,但仍有一个简单的解决方案:library(lubridate)
df <- data.frame(day_number=0:6) %>% # Your data
mutate(t_day_number = day_number +1) %>% # Add 1 to your existing day number
mutate(day_of_week = wday(t_day_number, label = TRUE)) # Use wday and switch on labels
day_number t_day_number day_of_week
1 0 1 Sun
2 1 2 Mon
3 2 3 Tue
4 3 4 Wed
5 4 5 Thu
6 5 6 Fri
7 6 7 Sat
select
来删除您不想要的列。x <- data.frame(wday=rep(0:6, 2))
x$wday_name <- factor(x$wday, levels=0:6,
labels=c("Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"))
x
# wday wday_name
# 1 0 Sunday
# 2 1 Monday
# 3 2 Tuesday
# 4 3 Wednesday
# 5 4 Thursday
# 6 5 Friday
# 7 6 Saturday
# 8 0 Sunday
# 9 1 Monday
# 10 2 Tuesday
# 11 3 Wednesday
# 12 4 Thursday
# 13 5 Friday
# 14 6 Saturday
as.character
。dat = data.frame(daynumber = c(1,5,6,0))
df <- data.frame(Number = 0:6,
Day = weekdays(x=as.Date(seq(7), origin="2017-10-01")))
dat$daynumber = df$Day[match(dat$daynumber,df$Number)]
dnum<-sample(0:6,10,replace=T)
var<-sample(LETTERS,10,replace=T)
df<-data.frame(dnum,var)
> df
dnum var
1 3 K
2 4 D
3 4 L
4 3 J
5 6 A
6 2 W
7 3 A
8 3 W
9 2 D
10 4 K
你可以创建一个包含星期几名称的数据库:
dnom<-c('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')
do<-0:6
dfo <- data.frame(dnom,do)
> dfo
dnom do
1 Sunday 0
2 Monday 1
3 Tuesday 2
4 Wednesday 3
5 Thursday 4
6 Friday 5
7 Saturday 6
现在,使用循环来比较您的数据框中的日期号码与数据库,并替换为星期几名称。
sub<-c()
for(i in 1 :nrow(df)){
d<-dfo[dfo$do==df$dnum[i],]
sub[i]<-as.character(d$dnom[1])
}
df$dnum<-sub
dnum var
1 Wednesday K
2 Thursday D
3 Thursday L
4 Wednesday J
5 Saturday A
6 Tuesday W
7 Wednesday A
8 Wednesday W
9 Tuesday D
10 Thursday K
这不是很优雅,但我希望能对你有所帮助。
祝好。