Suppose, I have this dataframe (integers).
df <- data.frame(date = c(20010101:20010103, 20050304, 20050506, 20220113, 20220216))
And I have the target date like this:
target_date = 2001
I want to extract only those values from df
of which first 4 integers match with the target date.
Result like this:
20010101 20010102 20010103
CodePudding user response:
We may use substr
to extract the first four character and then compare (==
) with target_date
to extract the subset of rows and pull the 'date' column
subset(df, substr(date, 1, 4) == target_date)$date
[1] 20010101 20010102 20010103
Or another option is to convert to Date
class, extract the year
and then filter
library(dplyr)
library(lubridate)
df %>%
filter(year(ymd(date)) == target_date)
date
1 20010101
2 20010102
3 20010103
CodePudding user response:
df[floor(df$date/10000) == target_date,]