Posts

Showing posts from April 2, 2019

lead or lag function to get several values, not just the nth

Image
Clash Royale CLAN TAG #URR8PPP 10 3 I have a tibble with a list of words for each row. I want to create a new variable from a function that searches for a keyword and, if it finds the keyword, creates a string composed of the keyword plus-and-minus 3 words. The code below is close , but, rather than grabbing all three words before and after my keyword, it grabs the single word 3 ahead/behind. df <- tibble(words = c("it", "was", "the", "best", "of", "times", "it", "was", "the", "worst", "of", "times")) df <- df %>% mutate(chunks = ifelse(words=="times", paste(lag(words, 3), words, lead(words, 3), sep = " "), NA)) The most intuitive solution would be if the lag function could do something like this: lead(words, 1:3) but that doesn't work. Obviously I could pretty quickly do this by hand ( paste(lead(words,3), lead(