【问题标题】:Add a column in R with season time在 R 中添加一个带有季节时间的列
【发布时间】:2022-08-10 15:03:19
【问题描述】:

我有一个这样的数据集,我想添加一个带有季节时间的列,如下所示:

Month Year Region Season
January 2019 NY Winter
February 2019 NY Winter
March 2019 NY Spring
September 2019 NY Fall

如何在 R 中编写一个代码,自动添加一个列,其中所有 1 月、2 月和 12 月都是冬季,所有 3 月、4 月和 5 月都是春天等等。

非常感谢您的帮助

季节 <- c(数据,春天 = “三月”,春天 = “四月”)

  • 嗨,您是否尝试过合并数据集?喜欢merge(df1, df2)

标签: r


【解决方案1】:

我们可以创建一个键值数据集并进行连接

library(dplyr)
keydat <- tibble(Month = month.name, 
   Season = rep(c("Winter", "Spring", "Summer", "Fall", "Winter"), 
      c(2, 3, 3, 3, 1)))
df1 <- left_join(df1, keydat)

-输出

df1
      Month Year Region Season
1   January 2019     NY Winter
2  February 2019     NY Winter
3     March 2019     NY Spring
4 September 2019     NY   Fall

数据

df1 <- structure(list(Month = c("January", "February", "March", "September"
), Year = c(2019L, 2019L, 2019L, 2019L), Region = c("NY", "NY", 
"NY", "NY")), class = "data.frame", row.names = c(NA, -4L))

【讨论】:

    【解决方案2】:

    在基础 R 中,您可以执行以下操作:

    df1$Season <- c('Winter', 'Spring', 'Summer', 'Fall')[
      1 + (match(df1$Month, month.name) %/% 3) %% 4]
    

    结果是:

    df1
    #>       Month Year Region Season
    #> 1   January 2019     NY Winter
    #> 2  February 2019     NY Winter
    #> 3     March 2019     NY Spring
    #> 4 September 2019     NY   Fall
    

    (使用 akrun 的可重现数据)

    【讨论】:

      猜你喜欢
      • 2017-03-11
      • 2022-08-19
      • 2017-12-29
      • 1970-01-01
      • 1970-01-01
      • 2016-10-28
      • 2023-04-07
      • 1970-01-01
      • 2021-08-06
      相关资源
      最近更新 更多