我想用一些可選參數編寫R函數。它應該通過兩個核心參數對一些數據進行子集分類,然後我希望可以選擇傳遞額外的約束條件。例如。具有可選通配符參數的R子集自定義函數
filter_func <- function(start_datetime, end_datetime, user=*, type=*){
as.data.frame(subset(df, format(df$datetime,"%Y-%m-%d %H:%M:%S") > start_datetime &
format(df$datetime,"%Y-%m-%d %H:%M:%S") < end_datetime) &
df$user == user &
df$type == type)
所以......如果我通過一個PARAM它,它限制對用戶或類型的列,但如果我不它使用通配符和列得到的一切?
我見過這裏的例子使用%in%
或grepl()
但這些似乎更多旨在那就是你有一個字符串的一部分,然後想休息...像new_york
變得既new_york_city
和new_york_state
......我不想要獲得任何與param不完全匹配的值!
編輯:現在的例子
所以......從這樣的理想去...
start | end | user | type |
-----------------|------------------|------|------|
2017-01-01 11:00 | 2017-01-01 20:00 | usr1 | typ1 |
2017-01-01 12:00 | 2017-01-01 19:00 | usr2 | typ2 |
2017-01-01 02:00 | 2017-01-01 03:00 | usr2 | typ1 |
2017-03-01 01:00 | 2017-03-01 09:00 | usr1 | typ2 |
2017-04-01 05:00 | 2017-04-01 07:00 | usr3 | typ4 |
2017-05-01 01:00 | 2017-05-01 08:00 | usr2 | typ5 |
用我的功能filter_func(2017-01-01 00:00, 2017-01-01 23:59)
打動了我:
start | end | user | type |
-----------------|------------------|------|------|
2017-01-01 11:00 | 2017-01-01 20:00 | usr1 | typ1 |
2017-01-01 12:00 | 2017-01-01 19:00 | usr2 | typ2 |
2017-01-01 02:00 | 2017-01-01 03:00 | usr2 | typ1 |
但如果我添加一個PARAM filter_func(2017-01-01 00:00, 2017-01-01 23:59, usr2)
start | end | user | type |
-----------------|------------------|------|------|
2017-01-01 12:00 | 2017-01-01 19:00 | usr2 | typ2 |
2017-01-01 02:00 | 2017-01-01 03:00 | usr2 | typ1 |
甚至filter_func(2017-01-01 00:00, 2017-01-01 23:59, usr2, typ2)
start | end | user | type |
-----------------|------------------|------|------|
2017-01-01 12:00 | 2017-01-01 19:00 | usr2 | typ2 |
使用單詞邊界,即'在年底\\ B' – akrun
可能會幫忙看看樣本數據和預期結果 – Bulat
@akrun,您能否提供更多示例?正如我在做'user ='\\ b''? – Huw