英文:
Quarter Conversion using casewhen
问题
我正在尝试创建一个函数,以使用case_when
函数将月份值转换为季度。
然后,我想利用mutate()
函数创建一个新的变量Qtr,并确定我在每个季度中看到多少观察值。
convert_to_qtr <- function(Month) {
case_when(
Month == "Jan" ~ "Q1",
Month == "Feb" ~ "Q1",
Month == "Mar" ~ "Q1",
Month == "Apr" ~ "Q2",
Month == "May" ~ "Q2",
Month == "Jun" ~ "Q2",
Month == "Jul" ~ "Q3",
Month == "Aug" ~ "Q3",
Month == "Sep" ~ "Q3",
Month == "Oct" ~ "Q4",
Month == "Nov" ~ "Q4",
Month == "Dec" ~ "Q4"
)
}
example_months <- c("Jan", "Mar", "May", "May", "Aug", "Nov", "Nov", "Dec")
convert_to_qtr(example_months)
df %>%
mutate(Qtr = convert_to_qtr(Month)) %>%
group_by(Qtr) %>%
count(Qtr)
然而,我得到的答案与我的教授的下拉框中的答案不同,所以我不确定我在我的R编码中是否做错了什么。
他看到的数字是161,071 85,588 100,227 142,651,而我看到的是152,174 165,778 205,615 174,592。
英文:
I am trying to create a function so I convert the month values to quarters using the case when function.
Then I want to leverage mutate() to create a new variable Qtr and determine how many observations I see in each quarter.
convert_to_qtr <- function(Month) {
case_when(
Month == "Jan" ~ "Q1",
Month == "Feb" ~ "Q1",
Month == "Mar" ~ "Q1",
Month == "Apr" ~ "Q2",
Month == "May" ~ "Q2",
Month == "Jun" ~ "Q2",
Month == "Jul" ~ "Q3",
Month == "Aug" ~ "Q3",
Month == "Sep" ~ "Q3",
Month == "Oct" ~ "Q4",
Month == "Nov" ~ "Q4",
Month == "Dec" ~ "Q4"
)
}
example_months <- c("Jan", "Mar", "May", "May", "Aug", "Nov", "Nov", "Dec")
convert_to_qtr(example_months)
df %>%
mutate(Qtr = convert_to_qtr(Month)) %>%
group_by(Qtr) %>%
count(Qtr)
However I am not getting the same answer as my professor in his drop down so I am not sure if I am doing something wrong in my r coding.
He sees the numbers 161,071 85,588 100,227 142,651
I am not getting that, I see 152174 165778 205615 174592
答案1
得分: 0
你可以按照以下方式编写该函数:
convert_to_qtr <- function(Month){
setNames(paste0("Q", rep(1:4, each = 3)), month.abb)[Month]
}
df %>%
mutate(Qtr = convert_to_qtr(Month)) %>%
count(Qtr)
Qtr n
1 Q1 29
2 Q2 24
3 Q3 26
4 Q4 21
英文:
You could write the function as below:
convert_to_qtr <- function(Month){
setNames(paste0("Q", rep(1:4,each=3)), month.abb)[Month]
}
df %>%
mutate(Qtr = convert_to_qtr(Month)) %>%
count(Qtr)
Qtr n
1 Q1 29
2 Q2 24
3 Q3 26
4 Q4 21
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论