本文介绍了在R中使用dplyr按月创建季节变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据集,该数据集包含一个名为month的变量,每个月作为一个字符。 dplyr是否有办法组合几个月来创建季节变量?我尝试了以下操作,但遇到了错误:
I have a dataset that has a variable called month, which each month as a character. Is there a way with dplyr to combine some months to create a season variable? I have tried the following but got an error:
data %>%
mutate(season = ifelse(month[1:3], "Winter", ifelse(month[4:6], "Spring",
ifelse(month[7:9], "Summer",
ifelse(month[10:12], "Fall", NA)))))
有错误:
Error in mutate_impl(.data, dots) : Column `season` must be length 100798 (the number of rows) or one, not 3
我是R的新手,所以非常感谢!
I am new to R so any help is much appreciated!
推荐答案
正确的语法应为
data %>% mutate(season = ifelse(month %in% 10:12, "Fall",
ifelse(month %in% 1:3, "Winter",
ifelse(month %in% 4:6, "Spring",
"Summer"))))
修改:可能是完成工作的更好方法
Edit: probably a better way to get the job done
temp_data %>%
mutate(
season = case_when(
month %in% 10:12 ~ "Fall",
month %in% 1:3 ~ "Winter",
month %in% 4:6 ~ "Spring",
TRUE ~ "Summer"))
气象季节
temp_data %>%
mutate(
season = case_when(
month %in% 9:11 ~ "Fall",
month %in% c(12, 1, 2) ~ "Winter",
month %in% 3:5 ~ "Spring",
TRUE ~ "Summer"))
这篇关于在R中使用dplyr按月创建季节变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!