[英]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.
但是,在 R 中有很多函数可以处理字符串,我认为这会让人非常困惑。 So my easy question would be:
所以我的简单问题是:
I have this vector of format Date
我有这个格式
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.
但我基本上所做的只是在字符向量中每个元素的 substring 上应用某种简单的正则表达式。 Anyone might have an idea on what is "best practice" in R?
任何人都可能知道 R 中的“最佳实践”是什么?
Since you have dates_nc
of class "Date", you can extract the date part of dates_nc
with days_to_extract
.由于您有
dates_nc
“日期”的 dates_nc,您可以使用days_to_extract
提取dates_nc
的日期部分。
subset_vec <- dates_nc[as.integer(format(dates_nc, '%d')) %in%
as.integer(days_to_extract)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.