Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

string - 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?

question from:https://stackoverflow.com/questions/65843238/match-a-substring-for-each-element-in-a-character-vector-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...