Home > Software design >  Label a dataframe with if or ifelse and grepl
Label a dataframe with if or ifelse and grepl

Time:10-26

I have a dataset that captures the data of two e-learning modules. An e-learning module is indicated with a code that consists of numbers and letters. For example 1A21 and 2N34.

With the following code I am able to create a column in which I give the module code a name. To make it more understandable to me as a human.

df$Module <- ifelse(grepl("1A21", df$ModuleCode), "R-101", "R-201")

The code works like a charm. However, I am curious, how does it work if your dataframe starts to capture data of more than two e-learning modules? How would one solve this?

If this question is a duplicate, I apologize in advance.

CodePudding user response:

Ok, lets assume there are 3 codes: 1A21, 2N34, 3D56 with names: "R-101", "R-201", "R-301".

df$Module <- ifelse(grepl("1A21", df$ModuleCode), "R-101",
                    ifelse(grepl("2N34", df$ModuleCode),  "R-201", "R-301")

So, instead of the third argument we insert a new level of ifelse.

CodePudding user response:

I am not understanding your renaming logic. But following my example you are able to assign each ModuleCode any module name.

library(tidyverse)
 df <- tibble::tibble(ModuleCode = c("1A21", "2N34", "3P04"))
 df
# A tibble: 3 x 1
  ModuleCode
  <chr>     
1 1A21      
2 2N34      
3 3P04      
 df %>% dplyr::mutate(Module = dplyr::case_when(
     grepl("1A21",ModuleCode) ~ "R-101",
     grepl("2N34", ModuleCode) ~ "R-201",
     grepl("3P04", ModuleCode) ~ "R-301"
 ))
# A tibble: 3 x 2
  ModuleCode Module
  <chr>      <chr> 
1 1A21       R-101 
2 2N34       R-201 
3 3P04       R-301 
  • Related