简体   繁体   中英

Match a substring for each element in a character vector in R

I know this is no new question. However, there are so many functions to work with strings in R it can get really confusing I think. So my easy question would be:

I have this vector of format Date

 dates_nc
 [1] "2016-01-01" "2016-01-02" "2016-01-03" "2016-01-04" "2016-01-05" "2016-01-06"
 [7] "2016-01-07" "2016-01-08" "2016-01-09" "2016-01-10" "2016-01-11" "2016-01-12"
[13] "2016-01-13" "2016-01-14" "2016-01-15" "2016-01-16" "2016-01-17" "2016-01-18"
[19] "2016-01-19" "2016-01-20" "2016-01-21" "2016-01-22" "2016-01-23" "2016-01-24"
[25] "2016-01-25" "2016-01-26" "2016-01-27" "2016-01-28" "2016-01-29" "2016-01-30"
[31] "2016-01-31"

and this character-vector

> days_to_extract
[1] "12" "11" "10"

And I just want to extract the right days from all of those days. I feel like there are so many options. But what I essentially do is just apply some kind of easy regular expression over a substring of each element in a character vector. Anyone might have an idea on what is "best practice" in R?

Since you have dates_nc of class "Date", you can extract the date part of dates_nc with days_to_extract .

subset_vec <- dates_nc[as.integer(format(dates_nc, '%d')) %in% 
                       as.integer(days_to_extract)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM