0

As an example, suppose I have this data:

key <- data.frame(num=c(1,2,3,4,5), month=c("January", "Feb", "March", "Apr", "May"))
data <- c(4,2,5,3)

I want to create a new vector, data2 using the mapping of num to month contained in key. I can do this manually using case_when by doing lots of if statements at once:

library(dplyr)
data2<-case_when(
    data==1 ~ "January",
    data==2 ~ "Feb",
    data==3 ~ "March",
    data==4 ~ "Apr",
    data==5 ~ "May"
)

However, say that I want to automate this process (maybe I actually have thousands of if statements) and utilize the mapping contained in key. Is this, or something like it, possible?

Here is a failed attempt at code:

data2 <- case_when(data=key$num ~ key$month)

What I am going for is a vector called data2 with these elements: c("Apr","Feb","May","March"). How can I do this?

bill999
  • 2,147
  • 8
  • 51
  • 103
  • 1
    I'm certain there is a way to do it with `case_when`, but this can be done via subsetting - `key$month[match(data, key$num)]` for instance. – thelatemail Jun 03 '19 at 23:45
  • 1
    `data2 <- data.frame(num = data) %>% left_join(key) %>% pull(month)`. (And you probably want to load `key` with `stringsAsFactors = F`) – Jon Spring Jun 03 '19 at 23:45
  • Ideally, it would use `case_when` so that I can do this with a function. The real reason I am asking has to do with this question: https://stackoverflow.com/questions/56411936/display-different-time-elements-at-different-speeds-in-gganimate/56418594?noredirect=1#comment99464431_56418594 See my comment to the answer. Hopefully one of these answers can apply there. – bill999 Jun 03 '19 at 23:50

1 Answers1

1

You can use match and base R indexing (also, set stringsAsFactors=FALSE when you initialize the data.frame, as I did below):

key <- data.frame(num=c(1,2,3,4,5), month=c("January", "Feb", "March", "Apr", "May"), stringsAsFactors = FALSE)
data2 <- key$month[match(data, key$num)]
data2
#[1] "Apr"   "Feb"   "May"   "March"
ThetaFC
  • 660
  • 3
  • 9