这是我的数据框的示例:
I UserID | Day_of_week | hour | min
#1 1 1 0 0
#2 1 1 0 30
#3 1 1 1 0
#4 1 1 1 30
#5 1 1 2 0
#6 1 1 2 30
... ... ... ... ...
#10 1 2 0 0
#11 1 2 0 30
#12 1 2 1 0
#13 1 2 1 30
... ... ... ... ...
Day_of_week列从1到7,其中:
2 =星期一,3 =星期二...... 6 =星期五
和7和1分别是周六和周日。
我想在Day_of_Week的列中更改星期的名称。像这样:
I UserID | Day_of_week | hour | min
#1 1 Sunday 0 0
#2 1 Sunday 0 30
#3 1 Sunday 1 0
... ... ... ... ...
#10 1 Monday 0 0
#11 1 Monday 0 30
#12 1 Monday 1 0
#13 1 Monday 1 30
... ... ... ... ...
答案 0 :(得分:3)
只需使用矢量。
MIMEText()
答案 1 :(得分:2)
library(expss)
#Creating a sample dataset like yours
Day_of_week <- c(1,7,1,7,1,3,2,2,7,2,2,4,3,5,3)
userid <- c(1,3,1,1,1,3,2,2,4,4,3,3,32,3,3)
TableExample <- as.data.frame(cbind(userid, Day_of_week))
#Creating a week day reference table
DayID <- c(1,2,3,4,5,6,7)
DayName <- c("Sunday", "Monday", "Tuesday", "Wed", "Thur", "Friday", "Sat")
Weektable <- as.data.frame(cbind(DayID,DayName))
#Vlookup formula to look for x in the referencetable
FindWeekFunc <- function(x){
vlookup(x,Weektable,2)}
#maply to find teh result
TableExample$Name_of_Day <- mapply(FindWeekFunc, Day_of_week)
答案 2 :(得分:1)
我认为您可以将列转换为因子变量。
您可以尝试下面的内容
df$day_of_week <- factor(df$day_of_week,
labels = c("Sunday", "Monday","Tuesday","Wednesday", "Thursday", "Friday", "Saturday"),
levels = c(1,2,3,4,5,6,7))
我希望这应该有用。
答案 3 :(得分:0)
创建一个带数字的函数
library(dplyr)
day_of_week <- function(num){
ifelse(num == 1, "Sunday",
ifelse(num ==2, "Monday",
ifelse(num == 3, "Tuesday",
ifelse(num == 4, "Wednesday",
ifelse(num == 5, "Thursday",
ifelse(num == 6, "Friday", "Saturday"))))))
}
然后使用dplyr
来改变您的数据框
dat <-
data.frame(x = rnorm(10),
day = sample(1:7, 10, TRUE)) %>%
mutate(day_of_week = day %>% day_of_week())
> dat
x day day_of_week
1 -0.4235498649 4 Wednesday
2 1.0366219455 2 Monday
3 0.4280368042 7 Saturday
4 -1.0335602213 5 Thursday
5 -0.6016099023 5 Thursday
6 1.4246527069 2 Monday
7 -0.3303051311 6 Friday
8 -0.0009648844 4 Wednesday
9 1.0168062274 6 Friday
10 0.2896002781 7 Saturday
答案 4 :(得分:0)
如果您通过将数字添加到星期六的任何特定日期将数字转换为日期,则可以使用base::weekdays
功能:
df <- data.frame(I = c(1L, 2L, 3L, 4L, 5L, 6L, 10L, 11L, 12L, 13L),
UserID = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L),
Day_of_week = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L),
hour = c(0L, 0L, 1L, 1L, 2L, 2L, 0L, 0L, 1L, 1L),
min = c(0L, 30L, 0L, 30L, 0L, 30L, 0L, 30L, 0L, 30L))
df$weekday <- weekdays(as.Date('1970-01-01') + 2 + df$Day_of_week)
df
#> I UserID Day_of_week hour min weekday
#> 1 1 1 1 0 0 Sunday
#> 2 2 1 1 0 30 Sunday
#> 3 3 1 1 1 0 Sunday
#> 4 4 1 1 1 30 Sunday
#> 5 5 1 1 2 0 Sunday
#> 6 6 1 1 2 30 Sunday
#> 7 10 1 2 0 0 Monday
#> 8 11 1 2 0 30 Monday
#> 9 12 1 2 1 0 Monday
#> 10 13 1 2 1 30 Monday