我是R编程的新手。实际上我想根据几个月来映射季节(如冬季,夏季,季风,季后季)。我试过下面的代码。请指导我。
ifelse((air_quality$Month %in% c('12','01','02','04')),air_quality$Seasons = 'Winter',
ifelse((air_quality$Month %in% c('04','05','06')),air_quality$Seasons = 'Summer',
ifelse((air_quality$Month %in% c('07','08','09')),air_quality$Seasons = 'Monsoon','Post Monsoon')))
提前致谢。 AP
答案 0 :(得分:0)
在你的例子中看起来像“04”属于“冬天”和“夏天”。 如果我们假设一个月只属于一个季节而且季节是冬季,夏季,季风和季后季,则可以将月份转换为季节的方法之一是:
library(stringr) # to produce strings padded with zeros
air_quality <- data.frame(Month = str_pad(sample(1:12,12, replace=FALSE),
width = 2,
side = "left", pad="0"))
# Create a mapping vector and print it
( seasons <- c( rep("Winter",2),
rep("Summer",3),
rep("Monsoon",3),
rep("Postmonsoon",3),
"Winter") )
#[1] "Winter" "Winter" "Summer" "Summer" "Summer" "Monsoon" "Monsoon"
#[8] "Monsoon" "Postmonsoon" "Postmonsoon" "Postmonsoon" "Winter"
air_quality$Seasons <- seasons[ as.numeric(air_quality$Month) ]
air_quality
# Month Seasons
# 1 07 Monsoon
# 2 06 Monsoon
# 3 11 Postmonsoon
# 4 01 Winter
# 5 05 Summer
# 6 09 Postmonsoon
# 7 03 Summer
# 8 08 Monsoon
# 9 10 Postmonsoon
# 10 02 Winter
# 11 04 Summer
# 12 12 Winter