Reputation: 7693
I have a dataframe like as shown below
test_df <- data.frame("subject_id" = c(1, 1, 1, 2),
"date_1" = c("8/6/2009 11:54", "28/3/2009 19:54", "18/2/2009 1:54", "11/3/2009 2:54"))
I would like to extract the month
and day
from the date_1
field. So, I tried the below
test_df %>%
mutate(date_1 = lubridate::dmy_hm(date_1),
without_year = format(date_1, "%d/%m"))
However, this throws an error like as shown below
Error in format.default(date_1, "%d/%m") :
invalid 'trim' argument
I expect my output to be like as shown below
Upvotes: 0
Views: 147
Reputation: 39585
Also you can try with dplyr
and base R
:
test_df %>% mutate(date_1=as.Date(test_df$date_1,format = '%d/%m/%Y %H:%M'),
daymonth=format(date_1,'%d/%m'))
subject_id date_1 daymonth
1 1 2009-06-08 08/06
2 1 2009-03-28 28/03
3 1 2009-02-18 18/02
4 2 2009-03-11 11/03
Upvotes: 2
Reputation: 4358
using base-R
format( as.POSIXct(test_df$date_1, format= "%d/%m/%Y %H:%M"), "%d/%m")
[1] "08/06" "28/03" "18/02" "11/03"
Upvotes: 1
Reputation: 12451
test_df %>%
mutate(
asDate=lubridate::dmy_hm(date_1),
justDayMonth=paste0(lubridate::day(asDate), "/", lubridate::month(asDate)
)
)
subject_id date_1 asDate justDayMonth
1 1 8/6/2009 11:54 2009-06-08 11:54:00 8/6
2 1 28/3/2009 19:54 2009-03-28 19:54:00 28/3
3 1 18/2/2009 1:54 2009-02-18 01:54:00 18/2
4 2 11/3/2009 2:54 2009-03-11 02:54:00 11/3
Upvotes: 1