1

I have a column of random words, and some words contain the months (it could be anything such as Jan, or Dec), I want to be able to find those row numbers with months name. How can I do that?

df = tibble(word=c("asd","May","jbsd"))
grepl(c("Jan","Feb","Mar","Apr","May", etc), df[["word"]])
Subaru Spirit
  • 394
  • 3
  • 19

2 Answers2

2

You can use which with %in% to get the row number of the match.

which(df$word %in% month.abb)
#[1] 2

Note that mont.abb is locale-specific so if df$word is in English it is expected that your system locale is of the same language.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

Edit: just saw the comments, I let mine in case you want to have the month name

Using dplyr:

df %>%
  mutate(rownumber = row_number()) %>% 
  filter(word %in% month.abb)

Output:

# A tibble: 1 x 2
  word  rownumber
  <chr>     <int>
1 May           2
MonJeanJean
  • 2,876
  • 1
  • 4
  • 20
  • Thanks for the answer, but I want to know the row number for the word it's in and not just the word. – Subaru Spirit Jul 27 '21 at 11:19
  • 2
    Just edited, I'll let mine in case you want the month name with its row index. But if you just want the row number, RonakShah idea is more efficient @SubaruSpirit – MonJeanJean Jul 27 '21 at 11:26