2

I have the following data frame

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

I need to add another column tCode that gets calculated from Code column. Code has a wide range of values. For each given range, I need to have a specific value for tCode. I can't use cut function for example for this task. The range and the expected outcome are given to me. I can only think of this lengthy ifelse structure:

  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 feel that this is the best way to solve this problem. Are there better suggestions?.

BICube
  • 4,451
  • 1
  • 23
  • 44
  • You're doing recursion by hand. Represent the transformation you're making as a function. – Mulan Apr 03 '16 at 20:49
  • Perhaps see also [this](http://stackoverflow.com/questions/28181753/grouping-factor-levels-in-an-r-data-table) question of mine for more options – MichaelChirico Apr 03 '16 at 20:54

1 Answers1

7

Come up with a matching table and merge.

I'll do the first couple statements for brevity, hopefully you get the point:

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"]
MichaelChirico
  • 33,841
  • 14
  • 113
  • 198