Best way to replace long ifelse structure in R

I have the following dataframe

df = data.frame(Code=seq(80,105,1))

      

I need to add another column tCode

which is calculated from the column Code

. Code

has a wide range of values. For every given range, I need to have a specific value for tCode

. For example, for this task, I cannot use the function cut

. The range and expected result are given to me. I can only think of this lengthy structure ifelse

:

  df$tCode = ifelse(df$Code > 102, 81, 
                            ifelse(df$Code %in% seq(101,102,1),80,
                                   ifelse(df$Code %in% seq(99,100,1),79,
                                          ifelse(df$Code %in% seq(97,89,1),78,
                                                 ifelse(df$Code %in% seq(95,96,1),77,
                                                        ifelse(df$Code %in% seq(92,94,1),76,
                                                               ifelse(df$Code %in% seq(90,91,1),75,
                                                                      ifelse(df$Code %in% seq(88,89,1),74,
                                                                             ifelse(df$Code %in% seq(86,87,1),73,
                                                                                    ifelse(df$Code %in% seq(84,85,1),72,
                                                                                           ifelse(df$Code %in% seq(82,83,1),71,
                                                                                                  ifelse(df$Code %in% seq(80,81,1),70,1))))))))))))

      

I don't think this is the best way to solve this problem. Are there any better deals?

+2


source to share


1 answer


Come up with a suitable table and merge.

I'll make the first couple statements for brevity, I hope you get the idea:



library(data.table); setDT(df)

match_table <- 
  data.table(Code = c(89:102),
             tCode = c(rep(78, 9), 79, 79, 80, 80))

df[match.table, tCode := tCode, on = "Code"]

      

+5


source







All Articles