使用向量中的相关位置查找索引

时间:2019-11-21 15:29:10

标签: r indexing grep which

我为研究中的每个参与者提供了一个向量,描述了他们的饮食时间。例如,参与者1和2分别具有

> eating.period.1
 [1] "Day 1 (1/18/15)"     "    Breakfast"       "    Morning Snack"   "    Lunch"           "    Afternoon Snack"
 [6] "    Dinner"          "    Evening Snack"   "Day 2 (1/19/15)"     "    Breakfast"       "    Morning Snack"  
[11] "    Lunch"           "    Afternoon Snack" "    Dinner"          "    Evening Snack"   "Day 3 (1/20/15)"    
[16] "    Breakfast"       "    Morning Snack"   "    Lunch"           "    Afternoon Snack" "    Dinner"         
[21] "    Evening Snack"   "Average"   


> eating.period.2
 [1] "Day 1 (9/16/15)"     "    Breakfast"       "    Morning Snack"   "    Lunch"           "    Afternoon Snack"
 [6] "    Dinner"          "    Evening Snack"   "Day 2 (9/17/15)"     "    Breakfast"       "    Lunch"          
[11] "    Afternoon Snack" "    Dinner"          "    Evening Snack"   "Day 3 (9/21/15)"     "    Breakfast"      
[16] "    Lunch"           "    Dinner"          "    Evening Snack"   "Average"            

如何获取第X到X + 1天之间进食时间的索引?

1 个答案:

答案 0 :(得分:0)

我会用这样的东西:

find_index <- function(eating_period, day1, day2, meal){
  is <- grep(day1, eating_period, ignore.case = TRUE)
  ie <- grep(day2, eating_period, ignore.case = TRUE)
  im <- grep(meal, eating_period[(is+1):(ie-1)], ignore.case = TRUE)
  is+im
}
eating.period.2 <- c("Day 1 (9/16/15)",
"    Breakfast",
" Morning Snack",
"    Lunch",
"Afternoon Snack",
"Day 2 (9/17/15)")

find_index(eating.period.2, "day 1", "day 2", "breakfast")

输出

 # 2