0

Problem: I am trying to use mutate, ifelse, and grepl functions to pull out the data from lyrics3. Where every year is stored with artist name, lyrics, and records. I am trying to create a new variable called "decade" and store each year by its decade. Simply put, 1980-1989 is 1980s and so on. But instead function is renaming everything to 2010s and giving me a problem statement saying "argument 'pattern' has length > 1 and only the first element will be used" Here is my code below:

 lyrics3 <-lyrics3 %>%
  mutate(decade = ifelse(grepl("198", year), "1980s",
    ifelse(grepl("199", year), "1990s",
    ifelse(grepl("200", year), "2000s", "2010s"))))

3 Answers3

1

Have you considered using the case_when() function?

 library(tidyverse)

df <- data.frame(lyrics = c("a", "b", "c", "d"),
                 Year = c(1986, 1992, 2004, 2015))

df <- df %>%
  mutate(Decade = case_when(
    grepl("198",  Year) ~ "1980s",
    grepl("199",  Year) ~ "1990s",
    grepl("200",  Year) ~ "2000s",
    TRUE ~ as.character(Year)
    ))
Blue050205
  • 276
  • 2
  • 4
0

If you have year as number you can use some mathematical functions to get the decade. For example, with plyr::round_any.

x <- c(1981, 1989, 1990, 1983, 1992, 2005, 2010)
plyr::round_any(x, 10, f = floor)
#[1] 1980 1980 1990 1980 1990 2000 2010

paste0(plyr::round_any(x, 10, f = floor), 's')
#[1] "1980s" "1980s" "1990s" "1980s" "1990s" "2000s" "2010s"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

Inspired by @Ronak's solution if you don't know round_any.

library(tidyverse)

df <- tibble(yrs = c(1982, 1997, 2000, 2010, 1983))

df %>%
  mutate(paste0(floor(yrs/10), "0s"))
Gejun
  • 4,012
  • 4
  • 17
  • 22