我需要使用dplyr::mutate在R中输入一列,它可以返回前一个月+实际月份+下个月的第一个字母。
我的数据帧是这样的:
library(dplyr)
Months <- c(
"jan-50",
"feb-50",
"mar-50",
"apr-50",
"may-50",
"jun-50",
"jul-50",
"aug-50",
"sep-50",
"oct-50",
"nov-50",
"dec-50"
)
three_months <- c(
"DJF", # Is the same as D = December J = January and F = February
"JFM", # Is the same as J = January, F = February, M = March and so on...
"FMA",
"MAM",
"AMJ",
"MJJ",
"JJA",
"JAS",
"ASO",
"SON",
"OND",
"NDJ"
)
df <- data.frame(Months, three_months)
df
#Months three_months
#1 jan-50 DJF
#2 feb-50 JFM
#3 mar-50 FMA
#4 apr-50 MAM
#5 may-50 AMJ
#6 jun-50 MJJ
#7 jul-50 JJA
#8 aug-50 JAS
#9 sep-50 ASO
#10 oct-50 SON
#11 nov-50 OND
#12 dec-50 NDJ
df <- df %>%
mutate(three_months =
# Formula to initial letters of the past month + actual month + next month
)我如何使用这个公式来获取每个月相对缩写字母的过去值和下一个值?
我只能使用下面这样的命令来表示实际月份:
df <- df%>%
mutate(
three_months = abbreviate(Data, 1, strict=TRUE),
three_months = gsub('[1 2]', '', `3 months`),
three_months = toupper(`3 months`) # Shows the time t month initial letter
)谢谢!
发布于 2021-10-03 15:21:31
我认为最简单的方法是使用查找向量:
lookup <- c("jan"= "DJF",
"feb" = "JFM",
"mar" = "FMA",
"apr" = "MAM",
"may" = "AMJ",
"jun" = "MJJ",
"jul" = "JJA",
"aug" = "JAS",
"sep" = "ASO",
"oct" = "SON",
"nov" = "OND",
"dec" = "NDJ")
library(dplyr)
library(stringr)
df %>%
mutate(three_months = lookup[str_replace(Months, "(\\w+)-.*", "\\1")])这将返回
Months three_months
1 jan-50 DJF
2 feb-50 JFM
3 mar-50 FMA
4 apr-50 MAM
5 may-50 AMJ
6 jun-50 MJJ
7 jul-50 JJA
8 aug-50 JAS
9 sep-50 ASO
10 oct-50 SON
11 nov-50 OND
12 dec-50 NDJ发布于 2021-10-03 19:02:22
通过看到@Martin Gal的回答,我想:
df <- df %>%
mutate(`3 months` =
case_when(
month(Months) == 1 ~ "DJF",
month(Months) == 2 ~ "JFM",
month(Months) == 3 ~ "FMA",
month(Months) == 4 ~ "MAM",
month(Months) == 5 ~ "AMJ",
month(Months) == 6 ~ "MJJ",
month(Months) == 7 ~ "JJA",
month(Months) == 8 ~ "JAS",
month(Months) == 9 ~ "ASO",
month(Months) == 10 ~ "SON",
month(Months) == 11 ~ "OND",
month(Months) == 12 ~ "NDJ",
)
)因为我期待的是一个周期性的月度时间序列,所以这里的case_when也运行得很好。
发布于 2021-10-03 19:15:37
我们可以用regex_left_join做到这一点
library(fuzzyjoin)
regex_left_join(tibble(Months),
stack(setNames(three_months, tolower(month.abb))),
by = c("Months" = "ind")) %>%
select(-ind)
# A tibble: 12 × 2
Months values
<chr> <chr>
1 jan-50 DJF
2 feb-50 JFM
3 mar-50 FMA
4 apr-50 MAM
5 may-50 AMJ
6 jun-50 MJJ
7 jul-50 JJA
8 aug-50 JAS
9 sep-50 ASO
10 oct-50 SON
11 nov-50 OND
12 dec-50 NDJ https://stackoverflow.com/questions/69425971
复制相似问题