lundi 3 juin 2019

Do if then statement based on values inside data frame or vector

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?

Aucun commentaire:

Enregistrer un commentaire