2016-07-23 11 views
0

요일에 대한 데이터 프레임에 변수가 있습니다.요일 서식 지정 R

> str(g.2015.1990$DAY.OF.WEEK) 
Factor w/ 7 levels "Friday","Monday",..: 1 3 4 2 6 7 5 1 3 4 ... 

R은 이것을 요인으로 인식하지만 대신 이미 사용할 수있는 요일에 대한 특정 형식이 있습니까? 요일을 생성하거나 이미 가지고있는 날짜에 대해 요일을 지정하는 것에 관한 질문을 읽었습니다. 그러나, 나는 당신이 이미 가지고있는 변수의 형식을 요일로 바꾸는 것에 대해서는 읽지 않았다.

이것은 궁극적으로 내 연구와 관련이 없습니다. 하지만 형식이 올바르다면 앞으로 나아갈 수 있다고 생각합니다. 나는 이것이 어디서 올지 알 수 없다. 그러나 서열화가 문제가된다면 R은 분명히 시간 순서 (일요일, 월요일, 화요일 등)가 바람직한 알파벳 순서 (금요일, 월요일, 토요일 등)로 요인 변수를 배열합니다. 여기

내가 무엇을 시도했다입니다 :

dayx = as.Date(g.2015.1990$DAY.OF.WEEK, format = "%A") 
dayx = as.Date(as.character(g.2015.1990$DAY.OF.WEEK), format = "%A") 
dayx = strptime(g.2015.1990$DAY.OF.WEEK, format = "%A") 
dayx = strftime(as.character(g.2015.1990$DAY.OF.WEEK, format = "%A")) 
dayx = strptime(g.2015.1990$DAY.OF.WEEK, format = "%a") 
dayx = as.Date(g.2015.1990$DAY.OF.WEEK, format = "%a") 
dayx = as.Date(as.character(g.2015.1990$DAY.OF.WEEK), format = "%a") 
dayx = strftime(as.character(g.2015.1990$DAY.OF.WEEK, format = "%a")) 
dayx = strptime(sprintf('%s %04d', g.2015.1990$DATE, g.2015.1990$START.TIME, g.2015.1990$DAY.OF.WEEK), '%Y-%m-%d %H%M %a') 

각각 간단하게 오늘 날짜로 각 관측을 대체 할 것 같다

> dayx = as.Date(g.2015.1990$DAY.OF.WEEK, format = "%A") 
> dayx[1:25] 
[1] "2016-07-23" "2016-07-23" "2016-07-23" "2016-07-23" "2016-07-23" 
[6] "2016-07-23" "2016-07-23" "2016-07-23" "2016-07-23" "2016-07-23" 
[11] "2016-07-23" "2016-07-23" "2016-07-23" "2016-07-23" "2016-07-23" 
[16] "2016-07-23" "2016-07-23" "2016-07-23" "2016-07-23" "2016-07-23" 
[21] "2016-07-23" "2016-07-23" "2016-07-23" "2016-07-23" "2016-07-23" 

어떤 도움에 감사드립니다!

+1

당신은 수동으로 변수의 요소의 순서를 결정할 수없는 그런 짓을 것 너를 위해서? – thepule

답변

1

나는이 관련되어 있다고 생각 :

## This is the order you desire 
Weekdays <- c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday") 

## This simulates your `g.2015.1990$DAY.OF.WEEK` 
set.seed(0); test <- factor(sample(Weekdays, 100, replace = TRUE)) 

## This simulates what you see from `str(g.2015.1990$DAY.OF.WEEK)` 
str(test) 
# Factor w/ 7 levels "Friday","Monday",..: 3 2 6 5 3 2 3 3 5 5 ... 

## We can inspect levels 
levels(test) 
#[1] "Friday" "Monday" "Saturday" "Sunday" "Thursday" "Tuesday" 
#[7] "Wednesday" 

## This is what you should do to recode `test` for your desired order of levels 
tmp <- levels(test)[as.integer(test)] ## much more efficient than `tmp <- as.character(test)` 
test <- factor(tmp, levels = Weekdays) ## set levels when using `factor()` 

## This is what we see now 
str(test) 
# Factor w/ 7 levels "Sunday","Monday",..: 7 2 3 5 7 2 7 7 5 5 ... 

levels(test) 
# [1] "Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" 
# [7] "Saturday" 

그래서, 아예 시도 :

Weekdays <- c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday") 
tmp <- levels(g.2015.1990$DAY.OF.WEEK)[as.integer(g.2015.1990$DAY.OF.WEEK)] 
## use `Weekdays` defined above 
g.2015.1990$DAY.OF.WEEK <- factor(tmp, levels = Weekdays)