R 如何根据日期范围为季节创建新列? #制作一个可怕的数据帧: Ottawates
您可以使用R 如何根据日期范围为季节创建新列? #制作一个可怕的数据帧: Ottawates,r,for-loop,dataframe,character,R,For Loop,Dataframe,Character,您可以使用lubridate和ifelse根据日期范围查找季节。假设季节为冬季和其他季节,一种方法可以是: #make a horrible data frame: ottawadates <- as.Date(c("2016-08-04", "2016-09-03", "2016-02-15", "2016-03-29, "2016-09-27")) othervariable <- c(1, 2, 4, 5, 6) df = data.frame(othervariable,
lubridate
和ifelse
根据日期范围查找季节。假设季节为冬季和其他季节,一种方法可以是:
#make a horrible data frame:
ottawadates <- as.Date(c("2016-08-04", "2016-09-03", "2016-02-15", "2016-03-29, "2016-09-27"))
othervariable <- c(1, 2, 4, 5, 6)
df = data.frame(othervariable, ottawadates)
#数据
Ottawates如果您的示例包含与您的数据格式相同的数据,您将得到更好的答案。因此,如果您的数据集使用日期,请在示例中使用日期。似乎相关:也相关:感谢您的建议。我更新了示例数据,使其采用日期格式。至于链接,谢谢。我只是不知道如何使用这些块,以便它们在我自己的数据集中迭代,并将正确的季节添加到新“季节”列的相应行中。谢谢。我将如何使用Spring之类的工具?只是更多的ifelse语句?你会怎么写?@hmnoidk请为spring添加范围,我可以修改我的答案。基本上和添加嵌套的ifelse
的方法相同。再次感谢。我添加了日期范围。@hmnoidk看看。
#data
ottawadates <- as.Date(c("2016-08-04", "2016-09-03", "2016-02-15"))
othervariable <- c(1, 2, 4)
df = data.frame(othervariable, ottawadates)
library(lubridate)
df$ottawadates <- ymd(df$ottawadates)
#Evaluate season
df$season <- ifelse((month(df$ottawadates) %in% c(1, 2)) |
(month(df$ottawadates) == 12L & day(df$ottawadates) >= 21L) |
(month(df$ottawadates) == 3L & day(df$ottawadates) <= 19L),
"Winter",
ifelse( (month(df$ottawadates) %in% c(4, 5)) |
(month(df$ottawadates) == 3L & day(df$ottawadates) >= 20L) |
(month(df$ottawadates) == 6L & day(df$ottawadates) <= 20L),
"Spring",
ifelse( (month(df$ottawadates) %in% c(7, 8)) |
(month(df$ottawadates) == 6L & day(df$ottawadates) >= 21L) |
(month(df$ottawadates) == 9L & day(df$ottawadates) <= 21L),
"Summer", "Fall")))
df
# othervariable ottawadates season
#1 1 2016-08-04 Summer
#2 2 2016-09-03 Summer
#3 4 2016-02-15 Winter