我有月度資料,我想為該期間添加另一列。該列會說 M01 表示 1 月,M02 表示 2 月,M03 表示 3 月,依此類推。有沒有辦法做到這一點?
這就是我所擁有的:
unemployment = data.frame(Month = c("Sept 2002", "Oct 2002", "Nov 2002", "Dec 2002", "Jan 2003", "Feb 2003"),
Total = c(5.7, 5.7, 5.9,
6, 5.8, 5.9))
> unemployment
Month Total
1 Sept 2002 5.7
2 Oct 2002 5.7
3 Nov 2002 5.9
4 Dec 2002 6.0
5 Jan 2003 5.8
6 Feb 2003 5.9
這就是我要的:
Month Period Total
1 Sept 2002 M09 5.7
2 Oct 2002 M10 5.7
3 Nov 2002 M11 5.9
4 Dec 2002 M12 6.0
5 Jan 2003 M01 5.8
6 Feb 2003 M02 5.9
編輯 更新代碼以顯示所有 12 個月
structure(list(Month = c("Jan", "Feb", "Mar", "Apr", "May", "June"
), Year = c("2003", "2003", "2003", "2003", "2003", "2003"),
Unemp_percent = c(5.8, 5.9, 5.9, 6, 6.1, 6.3)), row.names = 5:10, class = "data.frame")
uj5u.com熱心網友回復:
您可以在內置資料中使用mutateandgsub和前 3 個字母matchmonth.abb
library(dplyr)
unemployment |>
mutate(.after = Month,
Period = paste0("M", match(gsub("(.{3})(.*)", "\\1", Month ), month.abb)))
Month Period Total
1 Sept 2002 M9 5.7
2 Oct 2002 M10 5.7
3 Nov 2002 M11 5.9
4 Dec 2002 M12 6.0
5 Jan 2003 M1 5.8
6 Feb 2003 M2 5.9
uj5u.com熱心網友回復:
使用dplyr:
unemployment %>%
mutate(Period = case_when(grepl("Jan",Month) ~ "M01",
grepl("Feb",Month) ~ "M02",
grepl("Mar",Month) ~ "M03",
grepl("Apr",Month) ~ "M04",
grepl("May",Month) ~ "M05",
grepl("June",Month) ~ "M06",
grepl("July",Month) ~ "M07",
grepl("Aug",Month) ~ "M08",
grepl("Sept",Month) ~ "M09",
grepl("Oct",Month) ~ "M10",
grepl("Nov",Month) ~ "M11",
grepl("Dec",Month) ~ "M12"))
uj5u.com熱心網友回復:
只需制作月份和期間的參考表,然后left_join。
library(tidyverse)
months <- data.frame(mo = c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"),
Period = paste0("M", 1:12))
unemployment %>%
mutate(mo = str_extract(Month, "^[:alpha:] ")) %>%
left_join(months, by = "mo")
Month Total mo Period
1 Sept 2002 5.7 Sept M9
2 Oct 2002 5.7 Oct M10
3 Nov 2002 5.9 Nov M11
4 Dec 2002 6.0 Dec M12
5 Jan 2003 5.8 Jan M1
6 Feb 2003 5.9 Feb M2
uj5u.com熱心網友回復:
這是另一種選擇:
unemployment %>%
mutate(month = gsub("(^.{3}).*", "\\1", Month),
Period = paste0("M", as.numeric(factor(x$month, month.abb)))) %>%
select(Month, Period, Total)
輸出:
Month Period Total
1 Sept 2002 M9 5.7
2 Oct 2002 M10 5.7
3 Nov 2002 M11 5.9
4 Dec 2002 M12 6.0
5 Jan 2003 M1 5.8
6 Feb 2003 M2 5.9
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/522836.html
標籤:r数据框日期
下一篇:軸不會在ggplot中從0開始
