使用现有的“日期”变量;将月份和星期变量添加到数据框中[重复]

问题描述 投票:0回答:1

我有一个名为Covid19的数据框,它包含一个名为Date的变量。我想从Date变量创建两个新变量Month和Week。The output must look as in the image我写的代码是:

Covid19_df <- Covid19_df$Date %>% mutate(Month = lubridate::month(date), 
                Week = lubridate::week(date))

但出现错误

Error in UseMethod("mutate_") : 
  no applicable method for 'mutate_' applied to an object of class "Date"

任何人都可以给我一个可能的解决方案,或者新代码获得所需的输出。

r dataframe dplyr lubridate
1个回答
1
投票

您正在寻找的语法是:

library(dplyr)

Covid19_df <- Covid19_df %>% 
                mutate(Month = lubridate::month(Date), 
                        Week = lubridate::week(Date))
© www.soinside.com 2019 - 2024. All rights reserved.